xcode 如何在swiftui中显示/隐藏API响应视图?

but5z9lq  于 2022-11-26  发布在  Swift
关注(0)|答案(1)|浏览(194)

我尝试在某个条件下显示视图,但数据来自API,因此代码在API响应之前执行,但我想在API响应之后运行代码,如何在swiftUI应用程序中执行该操作?

class DashboardViewModel: ObservableObject {
    
    var poCount:[TaskCount]?
    
    @State var totalApprovalCount = 0


func getData() {

    APIService.shared.makeApiTypeRequest(url: APIURLConstant.poTaskCountUrl, param: nil, methodType: .get, expecting: [TaskCount].self, passToken: true) { result in
                switch result {
                case .success(let respData):
                    DispatchQueue.main.async {
                        self.rcCount = respData
                        print("fetchRCCount called \(respData.count)")
                        if respData.count > 0 {
                            self.totalApprovalCount += respData[0].count ?? 0
                        }
                        
                        if respData.count > 1 {
                            self.totalApprovalCount += respData[1].count ?? 0
                        }
                    }
                case .failure(let error):
                    if error as! CustomError == CustomError.tokenExpired {
                        DispatchQueue.main.async {
                            
                        }
                    }
                }
            }

}

查看者:

struct DashboardCombinedView: View {
    @ObservedObject var dashboardModel = DashboardViewModel()
    var body: some View {
        VStack {
            
            if dashboardModel.totalApprovalCount > 0 {
                Text("My custom view")
            }
      }.onAppear(){
        dashboardModel.getData()
      }
}

条件if dashboardModel.totalApprovalCount〉0 {总是得到假,因为它取决于API响应,我如何在API调用后检查此条件?

scyqe7ek

scyqe7ek1#

要观察对象,应在视图中使用@StateObject,并按@Published标识符发布任何更改:

class DashboardViewModel: ObservableObject {
    @Published var totalApprovalCount = 0

    var poCount: [TaskCount]?

    func getData() {
        // calling api
    }
}

和视图:

struct DashboardCombinedView: View {
    @StateObject private var dashboardModel = DashboardViewModel()

    var body: some View {
        VStack {
            if dashboardModel.totalApprovalCount > 0 {
                Text("My custom view")
            }
        }
        .onAppear {
            dashboardModel.getData()
        }
    }
}

相关问题