CLLocation 提示一瞬间显示又消失

2024-02-05

在我的应用程序中,我尝试从 GPS 获取经度和纬度。为此,我必须询问用户是否有权访问他的位置。在我这样做之前,我添加到Info.plist这两个卢比:Privacy - Location When In Use Usage Description and Privacy - Location Always Usage Description,然后在AppDelegate我询问这样做的许可(SWIFT 3.0):

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

我可以看到UIAlertController运行应用程序时有一瞬间,但几乎在同一时间它消失了,我没有时间点击Allow而且我无法使用 GPS。如何修复它?

我的问题的有效解决方案:

我创建了单独的变量var locationManager = CLLocationManager() in class LocationManager and then I used it in function.


问题是本地化经理在授权提示出现之前对象正在被释放......requestWhenInUseAuthorization以延迟的方式运行,所以这个实例CLLocationManager从你下面被拉出来。

所以改变范围本地化经理到您的视图控制器类而不是局部变量。

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

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

}

您也可以选择范围CL位置管理器给您的应用程序委托。

这在2016 年全球开发者大会 video 核心位置最佳实践会议临近第 21 分钟时。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CLLocation 提示一瞬间显示又消失 的相关文章

随机推荐