「iPhone アプリ開発集中講座」という本を参考に、pythonなどで処理したjsonを取得して、そのデータを一覧表示するアプリを作ろうとしています。
ContentVidwのButton(action: {})で関数を呼び出して、Jsonから取得したデータをList表示するところまでは出来たのですが、Buttonを押さずに関数を実行するには、どのように書いたら良いのでしょうか?
下記の await bousaiDataList.getPopulation() をbuttonを押さずに、アプリを開いたタイミングで実行させたいです。
ContentView.swift
swift
1import SwiftUI 2 3struct ContentView: View { 4 5 @StateObject var bousaiDataList = BousaiData() 6 7 var body: some View { 8 9 VStack { 10 Text("Hello, world!") 11 .padding() 12 Button(action: { 13 Task { 14 await bousaiDataList.getPopulation() 15 } 16 }){ 17 Text("表示") 18 } 19 List(bousaiDataList.bousaiList) { bousai in 20 21 HStack() { 22 Text(bousai.area) 23 Text("\(bousai.population)") 24 Text(bousai.capital) 25 } 26 } 27 } 28 } 29}
BousaiData.swift
swift
1import SwiftUI 2import UIKit 3 4struct BousaiItem: Identifiable { 5 let id = UUID() 6 let area: String 7 let population: UInt 8 let capital: String 9} 10 11class BousaiData: ObservableObject { 12 13 struct ResultJson: Codable { 14 struct Item: Codable { 15 let area: String? 16 let population: UInt? 17 let capital: String? 18 } 19 let item: [Item]? 20 } 21 @Published var bousaiList: [BousaiItem] = [] 22 23 func getPopulation() async { 24 print("hello!") 25 26 guard let req_url = URL(string: 27 "https://hoge.com/population.json") else { 28 return 29 } 30 print(req_url) 31 32 do { 33 let (data, _) = try await URLSession.shared.data(from: req_url) 34 let decoder = JSONDecoder() 35 let json = try decoder.decode(ResultJson.self, from: data) 36 37 guard let items = json.item else { return } 38 39 DispatchQueue.main.async { 40 self.bousaiList.removeAll() 41 } 42 43 for item in items { 44 if let area = item.area, 45 let population = item.population, 46 let capital = item.capital { 47 let bousai = BousaiItem(area: area, population: population, capital: capital) 48 DispatchQueue.main.async { 49 self.bousaiList.append(bousai) 50 } 51 } 52 } 53 print(self.bousaiList) 54 } catch { 55 print("エラーが出ました") 56 } 57 } 58}
-> 今の実装だと、ボタンを押さないと表示されない
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/01/29 00:17
2022/01/30 06:06