Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Result with URLsession
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