0

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.
Viktor Simkó
  • 2,607
  • 16
  • 22

1 Answers1

2

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.

Richmond Watkins
  • 1,342
  • 9
  • 17
  • I have not set my class as the delegate of the location manager, so i don't know how it could call its delegate methods. – Viktor Simkó May 23 '16 at 19:11
  • 1
    Either way, I don't think it is a sync task so when it falls out of scope in a method it is deallocated and it's processes are ended. By setting it as a property it stays alive and is allowed to finish. – Richmond Watkins May 23 '16 at 19:16