Skip to content

Instantly share code, notes, and snippets.

@ytyubox
Last active May 7, 2019 14:24
Show Gist options
  • Save ytyubox/870d6f15335d62861aee620c3409dffb to your computer and use it in GitHub Desktop.
Save ytyubox/870d6f15335d62861aee620c3409dffb to your computer and use it in GitHub Desktop.
easy DataTask

Usage

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
        ...
        
      }
    }
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