URLSession.shared.CallBackDataTask(with: <#URLRequest#>) {
switch $0{
case .success(let success):
let data:Data = success.0
let reponse:HTTPURLResponse = success.1
...
case .failure(let error):
let error:Error = error
...
}
}
Last active
May 7, 2019 14:24
-
-
Save ytyubox/870d6f15335d62861aee620c3409dffb to your computer and use it in GitHub Desktop.
easy DataTask
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
extension URLSession{ | |
typealias URLResult = Result<(Data,URLResponse),Error> | |
typealias URLCallback = (URLResult)->Void | |
enum URLERROR:Error { | |
case nodata, reponseUnknow | |
} | |
func CallBackDataTask(with request:URLRequest, | |
callback:@escaping URLCallback){ | |
let task = dataTask(with: request) { (data, reponse, error) in | |
var result:URLResult | |
defer { | |
DispatchQueue.main.async { callback(result)} | |
} | |
if let error = error { | |
result = .failure(error) | |
return | |
} | |
guard let reponse = reponse as? HTTPURLResponse else { | |
result = .failure(URLERROR.reponseUnknow) | |
return | |
} | |
guard let data = data else { | |
result = .failure(URLERROR.nodata) | |
return | |
} | |
result = .success((data, reponse)) | |
} | |
DispatchQueue.global().async { | |
task.resume() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment