[英]CLLocation Prompt shows and disappears in one moment
在我的应用程序中,我尝试从GPS获取经度和纬度。 为此,我必须询问用户访问其位置的权限。 在我这样做之前,我向Info.plist
添加了这两条规则: Privacy - Location When In Use Usage Description
和Privacy - Location Always Usage Description
,然后在AppDelegate
我询问执行权限(SWIFT 3.0):
if CLLocationManager.locationServicesEnabled() == true {
let localisationManager = CLLocationManager()
localisationManager.requestWhenInUseAuthorization()
localisationManager.startUpdatingLocation()
}
我可以在运行应用程序时看到UIAlertController
片刻,但几乎在同一时间它消失了,我没有时间点击Allow
,我无法使用GPS。 怎么解决?
我的问题的工作解决方案:
我在class LocationManager and then I used it in function.
创建了单独的变量var locationManager = CLLocationManager()
class LocationManager and then I used it in function.
问题是localisationManager对象在授权提示出现之前被释放... requestWhenInUseAuthorization
以延迟方式运行,因此CLLocationManager
这个实例从你下面被拉出。
因此,将localisationManager的范围更改为View Controller类而不是局部变量。
class ViewController: UIViewController {
let localisationManager = CLLocationManager() // <-- scope to class
//...
function requestAuthorization() {
localisationManager.requestWhenInUseAuthorization()
}
}
您也可以将CLLocationManager范围扩展到您的app委托。
在会议的第21分钟, WWDC 2016视频核心位置最佳实践中很好地解释了这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.