Skip to content

Instantly share code, notes, and snippets.

@ahmedk92
ahmedk92 / RealmCompaction.Swift
Last active August 5, 2018 19:07
Fix for `mmap() failed: Cannot allocate memory ` in RealmSwift
// Credits: https://github.com/realm/realm-cocoa/issues/1159
func compact() {
let tmpPath = Realm.Configuration.defaultConfiguration.fileURL!.appendingPathExtension("bak")
try! Realm().writeCopy(toFile: tmpPath)
try! FileManager.default.replaceItem(at: Realm.Configuration.defaultConfiguration.fileURL!, withItemAt: tmpPath, backupItemName: nil, options: .usingNewMetadataOnly, resultingItemURL: nil)
}
// Usage:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
@ahmedk92
ahmedk92 / uiview-subview-travsersal.swift
Created November 27, 2016 09:03
UIView Subview Tree Traversal
extension UIView {
func traverseSubviewTree(action: (UIView) -> ()) {
for sv in self.subviews {
action(sv)
}
for sv in self.subviews {
sv.traverseSubviewTree(action)
}
}
var str = "one"
let actionOne = { [str = str] in
print("str = \(str)")
}
let actionTwo = {
print("str = \(str)")
}
extension String {
/**
Returns the same string ensuring digits are in Latin.
Useful in https requests, when the backend doesn't handle non-Latin digits.
Not for cross-locale real value conversions (e.g. 12,5 => 12.5).
*/
var withNumbersLatinized: String {
get {
var selfASNSString = self as NSString
let pattern = "\\d+"
@ahmedk92
ahmedk92 / Podfile.rb
Created December 11, 2017 21:50
Lock Pods Swift Version to 3.2
post_install do |installer|
# Your list of targets here.
myTargets = [‘Alamofire’, ‘FontBlaster’, ‘MenuItemKit’]
installer.pods_project.targets.each do |target|
if myTargets.include? target.name
target.build_configurations.each do |config|
config.build_settings[‘SWIFT_VERSION’] = ‘3.2’
end
end
@ahmedk92
ahmedk92 / UIButton+Blocks.m
Created February 25, 2018 09:32
Simple Block API for UIButton
#import <objc/runtime.h>
static void* kBlocksKey = &kBlocksKey;
@implementation UIButton (Blocks)
- (void)blocks_addBlockForTouchUpInside:(void (^)(void))block {
objc_setAssociatedObject(self, &kBlocksKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(blocks_tapped:) forControlEvents:UIControlEventTouchUpInside];
}
@ahmedk92
ahmedk92 / Podfile.rb
Last active March 5, 2018 09:29
Selective WholeModule Optimization
post_install do |installer|
targetsToOptimizeAtDebug = ['SwiftSoup']
installer.pods_project.targets.each do |target|
if targetsToOptimizeAtDebug.include? target.name
target.build_configurations.each do |config|
if config.name == "Debug"
config.build_settings['SWIFT_OPTIMIZATION_LEVEL'] = '-Owholemodule'
end
end
@ahmedk92
ahmedk92 / UIButton+Blocks.swift
Created March 13, 2018 07:58
Closure syntax for UIButton's addTarget
import UIKit
extension UIButton {
typealias BlockType = (UIButton) -> ()
private static var controlStatesBlockKey = "controlStatesBlockKey"
func add(block: @escaping BlockType, forControlEvents controlEvents: UIControlEvents) {
UIButton.controlStatesBlockKey += "\(controlEvents)"
var blocks = (objc_getAssociatedObject(self, &UIButton.controlStatesBlockKey) as? [BlockType]) ?? []
blocks.append(block)
var xml = "<ق>نص</ق>"
var pattern = "<ق>(.*)</ق>"
var regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
var textCheckingResult: NSTextCheckingResult? = regex?.firstMatch(in: xml, options: [], range: NSRange(location: 0, length: xml.count))
var matchRange: NSRange? = textCheckingResult?.range(at: 1)
var match: String? = nil
if let aRange = matchRange {
match = (xml as NSString).substring(with: aRange)
}
print("Found string '\(match ?? "")'")
@ahmedk92
ahmedk92 / UrlQueryEscaping.swift
Created April 8, 2018 14:25
Url Query Escaping
let queryParams = "{query}{&page, per_page, sort, order}"
let urlString = "https://api.github.com/search/repositories?q=" + queryParams.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url = URL(string: urlString)!