Skip to content

Instantly share code, notes, and snippets.

@raulriera
Last active January 15, 2016 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save raulriera/19a24cf7a8ac180cb0f6 to your computer and use it in GitHub Desktop.
Save raulriera/19a24cf7a8ac180cb0f6 to your computer and use it in GitHub Desktop.
public typealias URLSessionOperationCompletion = (data: NSData?, response: NSHTTPURLResponse?, error: NSError?) -> Void
public class URLSessionOperation: Operation {
private var task: NSURLSessionDataTask?
private var completionHandler: URLSessionOperationCompletion?
/**
Returns an instance of `URLSessionOperation`
- parameter session: The session that will be used for this request. The default value is `.sharedSession()`.
- parameter url: The URL with the location of the resource to request against.
- parameter completion: The block executed iff the request completes.
*/
public init(session: NSURLSession = .sharedSession(), url: NSURL, completion: URLSessionOperationCompletion) {
super.init()
name = url.absoluteString
task = session.dataTaskWithURL(url) { [weak self] (data: NSData?, response: NSURLResponse?, error: NSError?) in
self?.completeOperationWithBlock(completion, data: data, response: response as? NSHTTPURLResponse, error: error)
}
}
public override func cancel() {
super.cancel()
task?.cancel()
}
public override func start() {
if cancelled {
_finished = true
} else {
_executing = true
task?.resume()
}
}
// MARK: Private
private func completeOperationWithBlock(completion: URLSessionOperationCompletion, data: NSData?, response: NSHTTPURLResponse?, error: NSError?) {
if cancelled == false || error?.code != NSURLErrorCancelled {
dispatch_async(dispatch_get_main_queue()) {
completion(data: data, response: response, error: error)
}
}
completeOperation()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment