简体   繁体   中英

How to use Swift async/await for MKLocalPointsInterestRequests

For an app for visual impaired persons, I want to show POI's in a view. 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.

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 .

Thus, declare AppleData to be an ObservableObject and text to be @Published :

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

    ...
}

And the ContentView should designate that object as an @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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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