Viktor Simkó
Viktor Simkó

Reputation: 2627

Why do I need to store a CLLocationManager to get the users location in MKMapView?

I want to get the user's location by setting showUserLocation property of MKMapView to true.
If I create a CLLocationManager and store it in a property, it works just fine.
However if I do not store it, just call requestWhenInUseAuthorization() on it like this:

if locationManagerStatus != .AuthorizedWhenInUse {
    CLLocationManager().requestWhenInUseAuthorization()
}

then it says:

Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

Upvotes: 0

Views: 59

Answers (1)

Richmond Watkins
Richmond Watkins

Reputation: 1370

CLLocationManager has to "stay alive" to call its different delegate methods "didUpdateLocations", "didChangeAuthorizationStatus", etc. Even if you aren't using them it still has to be stored as a property to be used or else it will be deallocated when it false out of scope. I'd imagine this is because most of it's actions are async.

Upvotes: 2

Related Questions