我正在使用Swift和SwiftUI构建一个应用程序。在MainViewModel中,我有一个函数调用Api以从url获取JSON并进行反序列化。这是在async/await协议下完成的。 问题是,我从xcode收到了以下评论:“不允许从后台线程发布更改;确保通过像receive(on:)这样的运算符在模型更新时从主线程发布值。”在代码的这一部分:
func getCountries() async throws{
countries = try await MainViewModel.countriesApi.fetchCountries() ?? []
}
谁调用了这个函数:
func fetchCountries() async throws -> [Country]? {
guard let url = URL(string: CountryUrl.countriesJSON.rawValue ) else {
print("Invalid URL")
return nil
}
let urlRequest = URLRequest(url: url)
do {
let (json, _) = try await URLSession.shared.data(for: urlRequest)
if let decodedResponse = try? JSONDecoder().decode([Country].self, from: json) {
debugPrint("return decodeResponse")
return decodedResponse
}
} catch {
debugPrint("error data")
}
return nil
}
我想知道是否有人知道如何修复它。