CLLocation提示显示并在一瞬间消失
在我的应用程序,我尝试从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。 如何解决它?
我的问题的工作解决scheme:
我在class LocationManager and then I used it in function.
创build了单独的variablesvar locationManager = CLLocationManager()
class LocationManager and then I used it in function.
问题是在授权提示出现之前, localisationManager对象被释放… requestWhenInUseAuthorization
以延迟的方式运行,所以CLLocationManager
这个实例会从你的下面拉出来。
所以把localisationManager的范围改为你的View Controller类而不是本地variables。
class ViewController: UIViewController { let localisationManager = CLLocationManager() // <-- scope to class //... function requestAuthorization() { localisationManager.requestWhenInUseAuthorization() } }
您也可以将CLLocationManager范围扩展到您的应用程序委托。
WWDC 2016video核心位置最佳实践在本次会议的第21分钟附近很好地解释了这一点。