PiterPan PiterPan - 1 year ago 106
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

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

if CLLocationManager.locationServicesEnabled() == true {
let localisationManager = CLLocationManager()
localisationManager.requestWhenInUseAuthorization()
localisationManager.startUpdatingLocation()
}


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

Answer Source

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() {
   localisationManager.requestWhenInUseAuthorization() 
 }

}

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download