Trying to mock NSURLConnection
This file contains 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
| protocol URLSessionDataTaskProtocol { | |
| func resume() | |
| } | |
| extension NSURLSessionDataTask: URLSessionDataTaskProtocol { } |
This file contains 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
| typealias DataTaskResult = (NSData?, NSURLResponse?, NSError?) -> Void | |
| protocol URLSessionProtocol { | |
| func dataTaskWithURL(url: NSURL, completionHandler: DataTaskResult) -> URLSessionDataTaskProtocol | |
| } | |
| extension NSURLSession: URLSessionProtocol { } // ERROR: Type 'NSURLSession' does not conform to protocol 'URLSessionProtocol' |
Cool idea with the typealias, @eliperkins. I think the drawback to that approach is that it prevents URLSessionProtocol from being used as a concrete type, so a client wanting to use the service would have to become generic.
I'd suggest this variation for @joemasilotti:
protocol URLSessionDataTaskProtocol {
func resume()
}
extension NSURLSessionTask: URLSessionDataTaskProtocol {}
protocol URLSessionProtocol {
func dataTaskWithURL(url: NSURL, completionHandler: DataTaskResult) -> URLSessionDataTaskProtocol
}
typealias DataTaskResult = (NSData?, NSURLResponse?, NSError?) -> Void
extension NSURLSession: URLSessionProtocol {
func dataTaskWithURL(url: NSURL, completionHandler: DataTaskResult) -> URLSessionDataTaskProtocol {
return (dataTaskWithURL(url, completionHandler: completionHandler) as NSURLSessionDataTask) as URLSessionDataTaskProtocol
}
}
func useSession(session: URLSessionProtocol) {
session.dataTaskWithURL(NSURL(string: "http://apple.com")!, completionHandler: { (data, response, error) in
print("Data: \(data), response: \(response), error: \(error)")
}).resume()
}
useSession(NSURLSession(configuration: .defaultSessionConfiguration()))This does work, thanks @briancroom!
@briancroom @joemasilotti Do you guys have Swift 3 version of this? I'm getting a Type 'URLSession' does not conform to protocol 'URLSessionProtocol' on the extension URLSession: URLSessionProtocol line.
Also getting Expressions are not allowed at the top level on useSession( line.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't have complete context around this, but I think this gets you most of the way there: