14
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftUIでURL通信を伴うアプリを実装してみる

Posted at

Introduction

WWDCで大きな発表がありましたね、そうSwiftUI。
ただSwiftUIでAPIを使ったアプリはどう実装するんだと思い、
デモアプリを作ってみました。

Coding

  • 実装したこと
  • ContentViewにNetworkManagerをStateとしてプロパティにもつ
  • NetworkManagerのinitでリクエストを行う
  • レスポンスをNetworkManagerのプロパティにupdateする
  • updateされた時にViewへの通知を行う

※APIとModelに関してはお持ちのAPIで書き換えお願いします。

ContentView

struct ContentView : View {
    @State var networkManager = NetworkManager()
    
    var body: some View {
        NavigationView {
            List (
                networkManager.models.identified(by: \.name)
            ) {
                Text($0.name)
            }
            .navigationBarTitle(Text("Model"))
        }
    }
}

NetworkManager

class NetworkManager: BindableObject {
    var didChange = PassthroughSubject<NetworkManager, Never>()
    
    var models: [Model] = [] {
        didSet {
            didChange.send(self)
        }
    }
    
    init() {
        guard let url = URL(string: "https://xxx.json") else { return }
        
        URLSession.shared.dataTask(with: url) { (data, _, _) in
            guard let data = data else { return }
            let models = try! JSONDecoder().decode([Model.self], from: data)
            DispatchQueue.main.async {
                self.models = models
            }
        }.resume()
    }
}

Model

struct Model: Decodable {
    let name: String
}

Figure

image.png

Impression

SwiftUIでAPIからのView生成まで作ることができました。
既存のフレームワークより大分簡潔にコード量も少なく書くことができます。
まだまだ出来ることが未知なフレームワークですが、今後が楽しみです!

Reference

https://developer.apple.com/videos/play/wwdc2019/204/
SwiftUI Fetching JSON and Image Data with BindableObject - YouTube

14
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?