Skip to content

Instantly share code, notes, and snippets.

@donchan922
Last active April 3, 2020 12:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donchan922/a734edc9e863696f0b139a6a60c4e35a to your computer and use it in GitHub Desktop.
Save donchan922/a734edc9e863696f0b139a6a60c4e35a to your computer and use it in GitHub Desktop.
SwiftUIでAPI呼び出しでJSONをパースするサンプルコード
import SwiftUI
import Combine
struct Movie: Codable, Identifiable {
public var id: Int
public var name: String
public var released: String
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "title"
case released = "year"
}
}
public class MovieFetcher: ObservableObject {
@Published var movies = [Movie]()
init() {
load()
}
func load() {
guard let url = URL(string: "https://gist.githubusercontent.com/rbreve/60eb5f6fe49d5f019d0c39d71cb8388d/raw/f6bc27e3e637257e2f75c278520709dd20b1e089/movies.json") else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
DispatchQueue.main.async {
self.movies = try! JSONDecoder().decode([Movie].self, from: data!)
}
}.resume()
}
}
struct ContentView: View {
@ObservedObject var fetcher = MovieFetcher()
var body: some View {
VStack {
List(fetcher.movies) { movie in
VStack (alignment: .leading) {
Text(movie.name)
Text(movie.released)
.font(.system(size: 11))
.foregroundColor(Color.gray)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment