Created
November 12, 2019 11:36
-
-
Save surakamy/24a098bff5e15a2715ffb23577f12dab to your computer and use it in GitHub Desktop.
URL request 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
import SwiftUI | |
import Combine | |
struct Response: Codable { | |
var results: [Result] | |
} | |
struct Result: Codable { | |
var trackId: Int | |
var trackName: String | |
var collectionName: String | |
} | |
struct ContentView: View { | |
@State var results = [Result]() | |
var body: some View { | |
List(results, id: \.trackId) { item in | |
VStack(alignment: .leading) { | |
Text(item.trackName) | |
.font(.headline) | |
Text(item.collectionName) | |
} | |
} | |
.onReceive(loader) { results in | |
self.results = results | |
} | |
} | |
var loader = URLSession | |
.shared | |
.dataTaskPublisher(for: URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song")!) | |
.map { $0.data } | |
.decode(type: Response.self, decoder: JSONDecoder()) | |
.map { $0.results } | |
.catch { _ in Just([]) } | |
.receive(on: RunLoop.main) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment