Created
January 3, 2021 16:46
-
-
Save kharrison/89c70bb53ac87f0fb32ae87bf9c640bb to your computer and use it in GitHub Desktop.
Using Result with URLsession
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
public enum NetworkingError: Error { | |
case unknown | |
case unexpectedStatus(HTTPURLResponse) | |
} | |
extension URLSession { | |
func load(_ url: URL, | |
completionHandler: @escaping (Result<Data, Error>) -> Void) | |
-> URLSessionDataTask { | |
let task = dataTask(with: url) { data, response, error in | |
if let error = error { | |
completionHandler(.failure(error)) | |
} | |
guard let httpResponse = response as? HTTPURLResponse, | |
let data = data else { | |
completionHandler(.failure(NetworkingError.unknown)) | |
return | |
} | |
guard (200...299).contains(httpResponse.statusCode) else { | |
completionHandler(.failure(NetworkingError.unexpectedStatus(httpResponse))) | |
return | |
} | |
completionHandler(.success(data)) | |
} | |
task.resume() | |
return task | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment