Created
March 8, 2022 02:00
-
-
Save lotusirous/2905b01c1978cf7fdda6282d4ee029ad to your computer and use it in GitHub Desktop.
A good way to handle HTTP in swift combine
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
let url = URL(string: "https://postman-echo.com/time/valid?timestamp=2016-10-10")! | |
struct PostmanResponse: Decodable { | |
let valid: Bool | |
} | |
enum ApiError: Error { | |
case invalidServerResponse | |
} | |
let publisher = URLSession.shared.dataTaskPublisher(for: url) | |
.tryMap { data, response in | |
guard let res = response as? HTTPURLResponse, res.statusCode == 200 else { | |
throw ApiError.invalidServerResponse | |
} | |
return data | |
} | |
.decode(type: PostmanResponse.self, decoder: JSONDecoder()) | |
publisher.sink(receiveCompletion: { completion in | |
print(".sink() received the completion", String(describing: completion)) | |
switch completion { | |
case .finished: | |
break | |
case .failure(let anError): | |
print("received error: ", anError) | |
} | |
}, receiveValue: { value in | |
print(".sink() received value: \(value)") | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment