Skip to content

Instantly share code, notes, and snippets.

@bill1m
Last active March 31, 2020 16:34
Show Gist options
  • Save bill1m/a7b82296d323b0d02c88a8c15e697f1e to your computer and use it in GitHub Desktop.
Save bill1m/a7b82296d323b0d02c88a8c15e697f1e to your computer and use it in GitHub Desktop.
Processing URL Session Data Task Results with Combine
// https://developer.apple.com/documentation/foundation/urlsession/processing_url_session_data_task_results_with_combine
import Foundation
import Combine
let cancellable = URLSession.shared
.dataTaskPublisher(for: URL(string: "https://jsonplaceholder.typicode.com/users")!)
.tryMap() { element -> Data in
guard let httpResponse = element.response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw URLError(.badServerResponse)
}
return element.data
}
.decode(type: UsersList.self, decoder: JSONDecoder())
.sink(receiveCompletion: { print ("Received completion: \($0).") },
receiveValue: { userslist in
for userlist in userslist {
print(userlist)
}
})
struct UsersListElement: Codable {
let id: Int
let name, username, email: String
let address: Address
let phone, website: String
let company: Company
}
struct Address: Codable {
let street, suite, city, zipcode: String
let geo: Geo
}
struct Geo: Codable {
let lat, lng: String
}
struct Company: Codable {
let name, catchPhrase, bs: String
}
typealias UsersList = [UsersListElement]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment