Skip to content

Instantly share code, notes, and snippets.

@surakamy
Created November 12, 2019 11:36
Show Gist options
  • Save surakamy/24a098bff5e15a2715ffb23577f12dab to your computer and use it in GitHub Desktop.
Save surakamy/24a098bff5e15a2715ffb23577f12dab to your computer and use it in GitHub Desktop.
URL request with Combine
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