CLLocation提示立即显示并消失 [英] CLLocation Prompt shows and disappears in one moment
问题描述
在我的应用中,我尝试从GPS获取经度和纬度。为此,我必须询问用户有关访问其位置的权限。在此之前,我将添加到 Info.plist
这两个规则:隐私-使用时的位置用法说明
和隐私-始终使用位置描述
,然后在 AppDelegate
中询问执行权限的权限(SWIFT 3.0):
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()
}
我可以看到 UIAlertController
在运行应用程序时一会儿,但是几乎在同一时间它消失了,我没有时间点击 Allow
,我可以不要使用GPS。
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:
我在类LocationManager中创建了单独的变量
var locationManager = CLLocationManager()
,然后在函数中使用了它。
I created separate variables var locationManager = CLLocationManager()
in class LocationManager and then I used it in function.
推荐答案
问题是在授权提示出现之前,正在释放 localisationManager 对象。 .. requestWhenInUseAuthorization
以延迟的方式运行,因此 CLLocationManager
的实例从您的下方被拉出。
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 的范围更改为View Controller类,而不是局部变量。
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()
}
}
您也可以选择 CLLocationManager
You could alternatively scope the CLLocationManager to your app delegate.
这在 WWDC 2016 视频核心位置最佳做法中有很好的解释。会话21。
This is explained nicely in the WWDC 2016 video Core Location Best Practices near minute 21 of the session.
这篇关于CLLocation提示立即显示并消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!