[英]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.