我已经在swiftUI中启动了项目。当我在后端更改数据但列表视图未更新时,我从添加到数组列表的Web服务接收数据。
import Foundation
import SwiftUI
import Combine
var orders_List: [OrdersModel] = []
struct OrdersModel: Identifiable,Hashable{
var id: String = UUID().uuidString
let order_no: String
let seat_name: String
let seat_no: String
let time: String
init(id: String, order_no: String,seat_name:String,seat_no:String,time:String){
self.id = id
self.order_no = order_no
self.seat_name = seat_name
self.seat_no = seat_no
self.time = time
}
}
class Order_Manager: ObservableObject {
var objectWillChange = ObservableObjectPublisher()
var fetchedSongsResults = [orders_List] {
willSet {
objectWillChange.send()
}
}
init() {
fetch_orders()
}
func fetch_orders() {
let defaults = UserDefaults.standard
let parameters = ["tokken": "a56af0a01e137f61a44a93398195f5db","order_status":"Submitted"]
guard let url = URL(string: "https://www.appvelo.com/golfcourseios/api/OrderApis/fetch_status_based_orders") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
let posts = json["data"] as? [[String: Any]] ?? []
orders_List.removeAll()
for result in posts {
//print(json)
let id = result["id"] as! String
let order_no = result["order_no"] as! String
let seat_no = result["order_no"] as! String
let seat_name = result["seat_type_image"] as! String
let time = result["time"] as! String
let order_Model = OrdersModel(id: id,order_no: order_no, seat_name: seat_name, seat_no: seat_no,time:time)
orders_List.append(order_Model)
// print(order_Model)
}
} catch {
print(error)
}
}
}.resume()
}
}
struct ContentView: View {
var body: some View {
VStack{
List {
ForEach(orders_List){ person in
Text("\(person.order_no)")
}
}
}
}
}
答案 0 :(得分:0)
如评论中所述,您需要修复Combine语法:
class Order_Manager: ObservableObject {
@Published var fetchedSongsResults = [orders_List]
}
您需要删除var objectWillChange = ObservableObjectPublisher()