将传入数据的数量存储在 API 中

Store the number of incoming data in API

在 SwiftUI 中

我正在尝试计算 API 中的数据数量 在视图上显示

当我在同一个 class 中打印变量 @Published var counts = 0 时,我看到来自 API 的值已被保存

但是当它显示在 View 上时会出现默认值

是我传输数据的方法有误还是有其他问题?

class Api : ObservableObject{

@Published var counts = 0

func getData(complation: @escaping ([model]) -> ()) {
    
    guard let url = URL(string: "https://XXXXXX") else { return }
    let token = "28|cSXXXXXX"
    var request = URLRequest(url: url)
    
    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    
    URLSession.shared.dataTask(with: request) { data, responce, err in
        
        guard let data = data else { return }

        do {
            let dataModel = try JSONDecoder().decode([model].self, from: data)

            self.counts = dataModel.count
            
            DispatchQueue.main.async {
                complation(dataModel)
                
            }
        } catch {
            print("error: ", error)
        }
    }
    .resume()
}
}

此处查看

import SwiftUI

struct Tap1Section1: View {


@ObservedObject var countid = Api()
@State var modelname : [model] = [model(title: "")]

var body: some View {
    
    VStack {

        ForEach(modelname) { item in
           
            Text("\(countid.counts)")
        }
    }
    .onAppear {
        Api().getData { item in
            self.modelname = item
        }
    }
}
}

您可以尝试以下替代方法来获取模型的数量:

struct Tap1Section1: View {
    
    @StateObject var viewModel = Api() // <-- here
    
    var body: some View {
        VStack {
            Text("\(viewModel.models.count)")  // <-- here
            ForEach(viewModel.models) { item in  // <-- here
                Text(item.title)  // <-- here
            }
        }
        .onAppear {
            viewModel.getData()
        }
    }
}

//  -- here
struct Model: Identifiable, Decodable {
    let id = UUID()
    var title: String
}

class Api: ObservableObject {
    
    @Published var models: [Model] = []  // <-- here
    
    func getData() {
        guard let url = URL(string: "https://XXXXXX") else { return }
        let token = "28|cSXXXXXX"
        var request = URLRequest(url: url)
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        URLSession.shared.dataTask(with: request) { data, responce, err in
            guard let data = data else { return }
            do {
                let dataModel = try JSONDecoder().decode([Model].self, from: data)
                DispatchQueue.main.async {
                    self.models = dataModel  // <-- here
                }
            } catch {
                print("error: ", error)
            }
        }
        .resume()
    }
}