Skip to content

Instantly share code, notes, and snippets.

@lotusirous
Created March 8, 2022 02:00
Show Gist options
  • Save lotusirous/2905b01c1978cf7fdda6282d4ee029ad to your computer and use it in GitHub Desktop.
Save lotusirous/2905b01c1978cf7fdda6282d4ee029ad to your computer and use it in GitHub Desktop.
A good way to handle HTTP in swift combine
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