Fetching Data from Web API and Displaying Using SwiftUI
ContentView.swift
struct ContentView : View { @State var model = PostListViewModel() var body: some View { List(model.posts) { post in Text(post.title) } } }
PostList.swift
import SwiftUI import Combine final class PostListViewModel: BindableObject { init() { fetchPosts() } var posts = [Post](){ didSet{ didChange.send(self) } } private func fetchPosts(){ Webservice().getAllPosts { self.posts = $0 } } let didChange = PassthroughSubject<PostListViewModel,Never>() }
Post.swift
struct Post: Codable, Hashable, Identifiable{ let id: Int let title: String let body: String }
Webservice.swift
import Foundation class Webservice { func getAllPosts(completion: @escaping ([Post]) -> ()) { guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else{ fatalError("URL is not correct!") } URLSession.shared.dataTask(with: url) { data, _, _ in let posts = try! JSONDecoder().decode([Post].self, from: data!) DispatchQueue.main.async { completion(posts) } }.resume() } }
↓ JSONデータが、こんな感じで表示されます。