简体   繁体   English

如何使用 Swift 异步/等待 MKLocalPointsInterestRequests

[英]How to use Swift async/await for MKLocalPointsInterestRequests

For an app for visual impaired persons, I want to show POI's in a view.对于视障人士的应用程序,我想在视图中显示 POI。 I use code below.我使用下面的代码。 Although the lowest level ( requestNearbyLocations ) prints info to the debug screen, I'm not able to return this data ( locdata ) to the calling method, so nor to the view.尽管最低级别 ( requestNearbyLocations ) 将信息打印到调试屏幕,但我无法将此数据 ( locdata ) 返回到调用方法,因此也无法返回到视图。

Main extract of the code used:所用代码的主要摘录:

struct ContentView: View {    
    var Apple: AppleData = AppleData()
    
    var body: some View {
        Text(Apple.text)
            .onAppear {
                Apple.requestLoc()
            }
        } 
}

With

class AppleData {
    
    var text = ""
    
    func requestLoc() -> Void {
        Task {
            async let mytext = requestNearbyLocations()
            text = await mytext
        }
    }
    
    func requestNearbyLocations() async -> String {
        var region = MKCoordinateRegion()
        region.center = CLLocationCoordinate2D(latitude: 52.060049, longitude: 4.542196)
        
        var loctext = ""
        let request = MKLocalPointsOfInterestRequest(center: region.center, radius: 100.0)
        request.pointOfInterestFilter = MKPointOfInterestFilter(excluding: [.restaurant, .cafe])
        let search = MKLocalSearch(request: request)
        
        do {
            let response = try await search.start()
            print(response.mapItems)
            for item in response.mapItems {
                print( item.name! )
                loctext = item.name!
            }
        }
        catch {
            print(error)
        }
        return loctext
    }    
}

What have I missed here?我在这里错过了什么?

You want to “observe” AppleData , which should “publish” changes in text .你想“观察” AppleData ,它应该“发布” text的变化。

Thus, declare AppleData to be an ObservableObject and text to be @Published :因此,将AppleData声明为ObservableObject并将text声明为@Published

class AppleData: ObservableObject {
    @Published var text = ""

    ...
}

And the ContentView should designate that object as an @ObservedObject : ContentView应该将 object 指定为@ObservedObject

struct ContentView: View {
    @ObservedObject var apple = AppleData()

    var body: some View {
        Text(apple.text)
            .onAppear {
                apple.requestLoc()
            }
    }
}

See Managing Model Data in Your App .请参阅在您的应用程序中管理 Model 数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM