Last active
December 21, 2019 07:52
-
-
Save hlung/6bb2d4d356aa5b98770a75f75a08e807 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
extension URLSession { | |
func send<T: Decodable>(_ request: URLRequest, | |
completion: @escaping ((Result<T, Error>) -> Void)) { | |
let task = dataTask(with: request) { (data, response, error) in | |
if let data = data { | |
do { | |
let decoded = try JSONDecoder().decode(T.self, from: data) | |
completion(.success(decoded)) | |
} | |
catch let error { | |
completion(.failure(error)) // decoding error | |
} | |
} | |
else if let error = error { | |
completion(.failure(error)) // data task error | |
} | |
else { | |
completion(.failure(NSError())) // unknown error | |
} | |
} | |
task.resume() | |
} | |
} | |
// Usage example | |
let urlSession = URLSession(configuration: .default) | |
urlSession.send(request, completion: { (result: <Author, Error>) in | |
// consume result | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment