本文分别通过 Observation(iOS17以上) 以及 Combine(iOS17以下) 框架,实现 SwiftUI 的网络数据加载
通过定义 isLoading、error、users 在网络获取的不同阶段按需显示View
isLoading:是否转圈,显示 ProgressView
error:网络获取错误,通过 Text 显示
users:网络获取正常,通过 NavigationStack 显示
Observable
Observable 通过 async await 方式实现
关键代码
func loadData() async {
let (data, _) = try await URLSession.shared.data(from: url)
isLoading = false
do {
let decoder = JSONDecoder()
let reponse = try decoder.decode([User].self, from: data)
self.users = reponse
print("reponse success: users")
} catch {
print("reponse error1: \(error)")
}
}
Combine
Combine 通过 Publish 发布实现
关键代码
let publisher = URLSession.shared.dataTaskPublisher(for: url)
publisher
.decode(type: [User].self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.map { users in
print("publisher map")
self.users = users
}
.catch { error in
print("publisher catch")
return Just(self).map { dataModel in
dataModel.isLoading = false
dataModel.error = error
}
}
.eraseToAnyPublisher()
其他
具体代码:https://github.com/nicaho/LoadDataDemo
参考:https://www.hackingwithswift.com/guide/ios-swiftui/5/3/challenge