Skip to content

Instantly share code, notes, and snippets.

@frr149
Created October 30, 2015 17:11
Show Gist options
  • Save frr149/106685d167ee8f4028e6 to your computer and use it in GitHub Desktop.
Save frr149/106685d167ee8f4028e6 to your computer and use it in GitHub Desktop.
extension NSURLSession{
// This extension provides an API that hides any explicit use of GCD
// functions.
// Just make sure you use the correct closure to update your UI(completionHandler:) and
// everything should work fine.
// If you wish to understand this code and know more about GCD and how to
// run closures in the background, make sure to check the GCD course
/*
*
* downloadHandler: runs in the delegate queue (background)
* completionHandler: runs in the MAIN QUEUE. Use it to update your UI
*/
public func dataTaskWithRequest(request: NSURLRequest,
downloadHandler: (data: NSData? , response: NSURLResponse?, error: NSError?) -> Void,
completionHandler:()->Void) -> NSURLSessionDataTask{
return dataTaskWithRequest(request) { (data, response, error) -> Void in
// delegate queue
downloadHandler(data: data, response: response, error: error)
// Move to the MainQueue and run the completion block
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler()
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment