首页 > 解决方案 > 在 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))
    }
}

标签: iosswiftasynchronousswiftui

解决方案


这是可能的方法。使用 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!)")
        }
    }
}

推荐阅读