小弟我做了一個與php互動的view,
目前做法如下
流程為:
step1:點擊button
step2:傳送參數parameters至ViewModel
step3:ViewModel與php互動獲得回傳值(true/false)並指定給isrepeat
step4:此時view中的isrepeat則變為step3所得到的值
假設php回傳值皆為true
目前遇到的問題是,點擊第一次button時會獲得false,第二次會變成true
有沒有方法能讓第一次點擊時就變成true呢?
在View中,利用button發送parameters給ViewModel
php回傳json格式的數組獲得 true/false 值,並且指定給isrepeat這個變數
ViewModel.swift
class ViewModel: ObservableObject{
@Published var isrepeat = Bool()
@Published var items = [PostModel]()
let prefixUrl = "****"
// MARK: - check test for repeat data
func check(parameters:[String: Any]){
guard let url = URL(string: "\(prefixUrl)/check_test_repeat.php") else{
print("Not found url")
return
}
let data = try! JSONSerialization.data(withJSONObject: parameters)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = data
request.setValue("application", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(with: request){(data,res,error) in
if error != nil{
print("error", error?.localizedDescription ?? "")
return
}
do{
if let data = data{
let result = try JSONDecoder().decode(check_test.self, from: data)
DispatchQueue.main.asyncAfter(deadline: .now()+1){
self.isrepeat = result.isrepeat // 指定給isrepeat
}
} else {
print("No data")
}
} catch let JsonError{
print("fetch json error:", JsonError.localizedDescription)
}
}.resume()
}
}
view.swift
struct reservationviewText1: View {
@EnvironmentObject var RV: RV_information
@EnvironmentObject var viewModel: ViewModel
...
...
...
var body: some View {
VStack{
...
...
Button(action: {
let parameters: [String: Any] = ["STime": datetoSting(Time: RV.STime), "ETime": datetoSting(Time: RV.ETime)] // 傳入參數
self.viewModel.check(parameters: parameters) //執行model
print(self.viewModel.isrepeat)}){
HStack{
Image(systemName: "scribble.variable")
.font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
Text("check out")
.fontWeight(.semibold)
.font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
}
}
}
}
php回傳格式如下
{"isrepeat":true}