【SwiftUI】WebAPI を使ってみる

Fetching Data from Web API and Displaying Using SwiftUI

www.youtube.com

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データが、こんな感じで表示されます。

返信を残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA