Last active
March 31, 2020 16:34
-
-
Save bill1m/a7b82296d323b0d02c88a8c15e697f1e to your computer and use it in GitHub Desktop.
Processing URL Session Data Task Results with Combine
This file contains hidden or 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
// 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