前提・実現したいこと
SwiftUIを利用してアプリを開発しています。
データの編集を行い、複数の非同期処理が終わった後に画面の更新をし、確実に新しい値を表示したいです。
対象の仕様は以下のとおりです。
-
1.エンドポイント①にGETで接続し1番目の値を取得する
-
2、エンドポイント②にGETで接続し1の動作で取得した1番目の値を引数として渡す。
もともと設定させている2番目の値との合計をクロージャーを使い設定する
-
3、エンドポイント③にPUTで接続し、1番目の値を更新する
-
4,3で新しくした値を利用し、2の動作を行い更新後の1番目の値と2番目の値の合計を取得し表示したい
発生している問題
上記の1,2、3の動作までは正しく動くのですが、4の動作の時に最新の値が表示されません。
該当のソースコード
BaseView.swift
import SwiftUI struct BaseView: View { @EnvironmentObject var appState: AppState @State var totalNumber:Int = 0 var body: some View { VStack{ VStack{ Text("The first number:(appState.firstNumber!.firstNumber)") // 1.2の動作後10を表示 -> 3の動作後20を表示 Divider() Text("The total number:(totalNumber)") // 1.2の動作後30を表示 -> 3の動作後30を表示(40と表示したい) } .sheet(isPresented: $appState.isSheet,onDismiss: { appState.getFirstNumber() appState.getTotalNumber(firstNumber: appState.firstNumber!.firstNumber, total: {returnData in self.totalNumber = returnData }) }) { Sheet() } } .onAppear(){ appState.getFirstNumber() // 1の動作 appState.getTotalNumber(firstNumber: appState.firstNumber!.firstNumber, total: {returnData in self.totalNumber = returnData }) //2の動作 } } }
JosonModel.swift
import Foundation struct FirstNumber:Codable { var firstNumber:Int } struct SecondNumber:Codable { var secondNumber:Int }
AppState.swift
class AppState: ObservableObject { @Published var firstNumber:FirstNumber? @Published var secondNumber:SecondNumber? @Published var isSheet:Bool = false func getFirstNumber(){ // Set up the URL request let endpoint: String = "https://sample.com/api/first_nuber/" guard let url = URL(string: endpoint) else { print("Error: cannot create URL") return } let urlRequest = URLRequest(url: url) // set up the session let config = URLSessionConfiguration.default let session = URLSession(configuration: config) // make the request let task = session.dataTask(with: urlRequest) { (data, response, error) in // check for any errors guard error == nil else { print("error calling GET") print(error!) return } // make sure we got data guard let responseData = data else { print("Error: did not receive data") return } // parse the result as JSON, since that's what the API provides DispatchQueue.main.async { do{ self.firstNumber = try JSONDecoder().decode(FirstNumber.self, from: responseData) }catch{ print("Error: did not decode") return } } } task.resume() } func getTotalNumber(firstNumber:Int,total:@escaping(Int)->Void ){ // print("makeGetCallTotalTemp") // Set up the URL request let endpoint: String = "https://sample.com/api/total_number/" guard let url = URL(string: endpoint) else { print("Error: cannot create URL") return } let urlRequest = URLRequest(url: url) // set up the session let config = URLSessionConfiguration.default let session = URLSession(configuration: config) // make the request let task = session.dataTask(with: urlRequest) { (data, response, error) in // check for any errors guard error == nil else { print("error calling GET") return } // make sure we got data guard let responseData = data else { print("Error: did not receive data") return } // parse the result as JSON, since that's what the API provides DispatchQueue.main.async { do{ self.secondNumber = try JSONDecoder().decode(SecondNumber.self, from: responseData) let totalNumber = firstNumber + self.secondNumber!.secondNumber print(self.secondNumber!.secondNumber) // 20 total(totalNumber) }catch{ print("Error: did not decode") return } } } task.resume() } func makeUpDateFirstNumber(firstNumber:Int,finish:@escaping(Bool)->Void) { var isFinish:Bool = false let endpoint: String = "https://sample.com/api/first_number/" guard let url = URL(string: endpoint) else { print("Error: cannot create URL") return } var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "PUT" urlRequest.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") let newInfo:[String:Any]=["firstNumber": firstNumber] let jsonInfo: Data do { jsonInfo = try JSONSerialization.data(withJSONObject: newInfo, options: []) urlRequest.httpBody = jsonInfo } catch { print("Error: cannot create JSON from newInfo") return } let session = URLSession.shared let task = session.dataTask(with: urlRequest) { (data, response, error) in guard error == nil else { print("error calling Put") return } guard let responseData = data else { print("Error: did not receive data") return } guard let response = response as? HTTPURLResponse else { print("Error: did not response data") return } print("The response code is (response.statusCode)") // parse the result as JSON, since that's what the API provides do { guard (try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any]) != nil else { print("Could not get JSON from responseData as dictionary") return } } catch { print("error parsing response from PUT") return } DispatchQueue.main.async { isFinish = true finish(isFinish) } } task.resume() } }
Sheet.swift
import SwiftUI struct Sheet: View { @EnvironmentObject var appState: AppState @State var isFinish:Bool = false @Environment(.presentationMode) var presentationMode var body: some View { Button(action:{ appState.makeUpDateFirstNumber(firstNumber: 20, finish: {returnData in isFinish = returnData } // 3の動作 ) }){ Text("UPDATE") }.onChange(of: isFinish){ result in if result { self.presentationMode.wrappedValue.dismiss() } } } }
補足情報(FW/ツールのバージョンなど)
Xcode:Version 12.0.1
あなたの回答
tips
プレビュー