PiterPan PiterPan - 8 months ago 47
iOS Question

CLLocation Prompt shows and disappears in one moment

In my app I try to get longitude and latitude from GPS. To do that I have to ask user about permission to access to his location. Before I do that I add to

this two rulees:
Privacy - Location When In Use Usage Description
Privacy - Location Always Usage Description
, then in
I ask about permission doing it (SWIFT 3.0):

if CLLocationManager.locationServicesEnabled() == true {
let localisationManager = CLLocationManager()

I can see
for one moment while running the app, but almost in this same time it disappears and I have no time to tap
and I can't use GPS. How to fix it?


The issue is that localisationManager object is being deallocated before the authorization prompt appears ... requestWhenInUseAuthorization runs in a deferred manner, so this instance of CLLocationManager get pulled out from underneath you.

So change the scope of localisationManager to your View Controller class instead of a local variable.

class ViewController: UIViewController {
 let localisationManager = CLLocationManager()    // <-- scope to class

 function requestAuthorization() {


You could alternatively scope the CLLocationManager to your app delegate.

This is explained nicely in the WWDC 2016 video Core Location Best Practices near minute 21 of the session.