![](/img/trans.png)
[英]How can I prompt the user to turn on location services after user has denied their use
[英]Prompt user to allow location services after being denied without crashing
我面臨的問題是當我按下UIButton時-需要位置服務才能啟動操作。 但是,如果用戶在應用程序的首次啟動時拒絕其定位服務,則該應用程序將崩潰。
我試圖找到一種實現CLAuthorizationStatus .Denied的方法,但是我似乎找不到一種方法。 我似乎可以實現的唯一代碼是didChangeAuthorizationStatus,它僅在應用程序首次啟動時才啟動請求。
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
if status == .AuthorizedAlways || status == .AuthorizedWhenInUse
{
manager.startUpdatingLocation()
}
else
{
manager.requestWhenInUseAuthorization()
}
}
如果我按UIButton發送API請求,則如果位置服務被拒絕,則應用程序將崩潰。
我的問題是如何在按鈕的IBAction中實現一種方法,該方法將指導用戶轉到其設置並啟用位置服務。 :)
CLLocationManager
具有靜態函數authorizationStatus()
,您甚至可以在不初始化CLLocationManager
對象的情況下使用它來獲取當前授權狀態。
因此,在用戶按下按鈕時調用的功能中,您可以檢查授權狀態並采取相應的措施:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
lazy var locationManager = CLLocationManager()
...
func didPressButton(sender: UIButton) {
switch CLLocationManager.authorizationStatus() {
case .AuthorizedAlways, .AuthorizedWhenInUse:
locationManager.delegate = self
locationManager.startUpdatingLocation()
case .NotDetermined:
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
case .Denied:
print("Show Alert with link to settings")
case .Restricted:
// Nothing you can do, app cannot use location services
break
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
manager.startUpdatingLocation()
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.