Created
April 6, 2016 21:46
-
-
Save algal/862c30e47c1fff96816c97b191d594a1 to your computer and use it in GitHub Desktop.
Type-wrapper for dataTaskWithRequest
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
// known-good: Xcode 7.3, Swift 2.2 | |
import Foundation | |
public enum DataTaskResult { | |
case Success(data:NSData,response:NSURLResponse?) | |
case Error(error:NSError,response:NSURLResponse?) | |
} | |
extension NSURLSession { | |
public func dataTaskWithRequest(request:NSURLRequest, | |
completion:(DataTaskResult)->Void) -> NSURLSessionDataTask | |
{ | |
let t = self.dataTaskWithRequest(request) { (data, response, error) in | |
if let data = data { | |
completion(DataTaskResult.Success(data: data, response: response)) | |
} | |
else if let error = error { | |
completion(DataTaskResult.Error(error: error, response: response)) | |
} | |
else { | |
NSLog("ERROR: NSURLSession.dataTaskWithRequest(_:completion:) has violated its API contract by returning a result that contains neither an NSError nor an NSData.") | |
let err = NSError(domain: "com.alexisgallagher.dataTaskWithRequest", code: 10, userInfo: | |
[NSLocalizedFailureReasonErrorKey : "NSURLSession.dataTaskWithRequest(_:completion:) has violated its API contract by returning a result that contains neither an NSError nor an NSData.","result":response ?? NSNull()]) | |
completion(DataTaskResult.Error(error:err, response: response)) | |
} | |
} | |
return t | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment