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?
CodePudding user response:
You want to “observe” 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()
}
}
}