简体   繁体   English

CLLocation提示会在一瞬间显示并消失

[英]CLLocation Prompt shows and disappears in one moment

In my app I try to get longitude and latitude from GPS. 在我的应用程序中,我尝试从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): 在我这样做之前,我向Info.plist添加了这两条规则: Privacy - Location When In Use Usage DescriptionPrivacy - Location Always Usage Description ,然后在AppDelegate我询问执行权限(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. 我可以在运行应用程序时看到UIAlertController片刻,但几乎在同一时间它消失了,我没有时间点击Allow ,我无法使用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. 我在class LocationManager and then I used it in function.创建了单独的变量var locationManager = CLLocationManager() class LocationManager and then I used it in function.

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. 问题是localisationManager对象在授权提示出现之前被释放... requestWhenInUseAuthorization以延迟方式运行,因此CLLocationManager这个实例从你下面被拉出。

So change the scope of localisationManager to your View Controller class instead of a local variable. 因此,将localisationManager的范围更改为View Controller类而不是局部变量。

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

 //...
 function requestAuthorization() {
   localisationManager.requestWhenInUseAuthorization() 
 }

}

You could alternatively scope the CLLocationManager to your app delegate. 您也可以将CLLocationManager范围扩展到您的app委托。

This is explained nicely in the WWDC 2016 video Core Location Best Practices near minute 21 of the session. 在会议的第21分钟, WWDC 2016视频核心位置最佳实践中很好地解释了这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM