I have the following code:
class Locator : NSObject, ObservableObject
{
private let locationManager: CLLocationManager
private var authorizationContinuation: CheckedContinuation<CLAuthorizationStatus, Never>?
@Published var authorizationStatus: CLAuthorizationStatus
@Published var location: CLLocation?
@Published var error: Error?
override init()
{
locationManager = CLLocationManager()
authorizationStatus = locationManager.authorizationStatus
super.init()
locationManager.delegate = self
}
@MainActor func checkAuthorizationStatus() async -> CLAuthorizationStatus
{
let status = locationManager.authorizationStatus
if status == .notDetermined
{
return await withCheckedContinuation
{ continuation in
authorizationContinuation = continuation
locationManager.requestWhenInUseAuthorization()
}
}
else
{
authorizationStatus = status
return status
}
}
}
extension Locator : CLLocationManagerDelegate
{
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager)
{
authorizationStatus = manager.authorizationStatus
authorizationContinuation?.resume(returning: authorizationStatus)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print(error)
self.error = error
location = nil
}
}
The function checkAuthorizationStatus()
stores state in the form of authorizationContinuation
.
If checkAuthorizationStatus()
would be called a second time before authorizationContinuation?.resume(returning: authorizationStatus)
, this state will be overwritten and the first async call would never resume.
Is it possible that checkAuthorizationStatus()
is called multiple times and that this state is overwritten? If so, can it be prevented, or is there some way around it?