我尝试在某个条件下显示视图,但数据来自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调用后检查此条件?
1条答案
按热度按时间scyqe7ek1#
要观察对象,应在视图中使用
@StateObject
,并按@Published
标识符发布任何更改:和视图: