问题
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?
Working solution of my problem:
I created separate variables var locationManager = CLLocationManager()
in class LocationManager and then I used it in function.
回答1:
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.
来源:https://stackoverflow.com/questions/38465488/cllocation-prompt-shows-and-disappears-in-one-moment