-
-
Save touchopia/3f37fd88add648b517c8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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