I’m trying to turn CoreLocation request location into async/await by doing this
class LocationService: NSObject, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
//MARK: Set up the Location Manager Delegate
override init() {
super.init()
locationManager.delegate = self
}
var currentLocation: CLLocation {
get async throws {
return try await withCheckedThrowingContinuation { continuation in
// 1. Set up the continuation object
self.continuation = continuation
// 2. Triggers the update of the current location
locationManager.requestLocation()
}
}
}
}
this code works, when called directly from the UI
Button {
Task { try await locationService.currentLocation }
} label: {
Text("Get Location")
}
but it wont work when its called from another Task
Button(action: {
Task {
let result = try await APIService.shared.getLocation()
}
}) {
Label("Add Item", systemImage: "brain")
}
and then from APIService
func getLocation() async throws -> String? {
//...
try await locationService.currentLocation
}
if called this way, the CLLocationManagerDelegate delegate methods dont get called.