CLLocation Prompt shows and disappears in one moment

纵然是瞬间 提交于 2019-12-10 17:56:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!