ios - 在 SwiftUI 视图中显示异步调用的结果
问题描述
如何在 SwiftUI 视图中显示异步调用的结果。在下面的代码中,我想要一个文本来显示调用 addressFor(location) 的成功结果。
import SwiftUI
import CoreLocation
struct ContentView: View {
var location: CLLocation
var body: some View {
Text("Hello, World!")
// How can I have a Text here that shows the success result of the completion coming from addressFor(location)
}
private func addressFor(_ location: CLLocation, completion: @escaping (Result<String, Error>) -> Void) {
let geocoder: CLGeocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { (placeMark, error) in
if error == nil {
if let firstPlaceMark = placeMark?.first {
completion(.success(firstPlaceMark.name ?? "" + " - " + (firstPlaceMark.locality ?? "")))
}
} else {
completion(.failure(error!))
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(location: CLLocation(latitude: 39.8333333, longitude: -98.585522))
}
}
解决方案
这是可能的方法。使用 Xcode 12 / iOS 14 测试。
@State private var name: String?
var body: some View {
VStack {
Text("Hello, World!")
.onAppear {
addressFor(location) { result in
let value = try? result.get()
self.name = value ?? "unknown"
}
}
if name != nil {
Text("Result: \(name!)")
}
}
}
推荐阅读
- gradle - 无法将“字符串”分配给“T”
- flutter - SemanticsService.announce 在颤振中
- java - 如何使用路径类?
- c++ - `typename` 不应该只用在模板函数或模板类中吗?
- scheme - 在 Guile 中跟踪 - 如何在 Guile 方案中进行跟踪
- javascript - Html 如何在我的模板中包含脚本?
- javascript - 如何处理覆盖固定元素的Android键盘?
- python - 如何通过在 python 中使用 selenium webdriver 从 html 表中的特定行获取数据
- python - 使用 lambda 从另一个函数传递参数
- html - 为什么div有内容时位置会发生变化?