Skip to content

Instantly share code, notes, and snippets.

@zonble
Last active February 17, 2016 13:27
Show Gist options
  • Save zonble/3d0c31fd3de90a75abde to your computer and use it in GitHub Desktop.
Save zonble/3d0c31fd3de90a75abde to your computer and use it in GitHub Desktop.
import UIKit
let SingletonErrorDomain = "SingletonErrorDomain"
class Singleton {
static let sharedInstance = Singleton()
var activeTask :NSURLSessionDataTask?
final func getURL(URLString :String, HTTPMethod :String, completion :(NSDictionary?, NSError?) -> Void) {
let request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: URLString)
request.HTTPMethod = HTTPMethod
self.activeTask?.cancel()
self.activeTask = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
self.activeTask = nil
if error != nil {
completion(nil, error)
return
}
guard let data = data else {
completion(nil, NSError(domain: SingletonErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("No data fetched", comment: "")]))
return
}
guard let parsedDictionary = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary else {
completion(nil, NSError(domain: SingletonErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("JSON error", comment: "")]))
return
}
completion(parsedDictionary, nil)
}
self.activeTask?.resume()
}
}
//var semaphore = dispatch_semaphore_create(0)
//
//Singleton.sharedInstance.getURL("https://raw.githubusercontent.com/g0v/hack.g0v.tw/master/g0v.json", HTTPMethod: "GET") {dictionary, error in
// if let dictionary = dictionary {
// print("\(dictionary)")
// }
// dispatch_semaphore_signal(semaphore)
//}
//dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment