Skip to content

Instantly share code, notes, and snippets.

@hlung
Last active December 21, 2019 07:52
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hlung/6bb2d4d356aa5b98770a75f75a08e807 to your computer and use it in GitHub Desktop.
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