2017-11-04 82 views
0

當用戶在MainViewController如何檢查是否用戶點擊不上NSLocationAlwaysAndWhenInUseUsageDescription雨燕3.2

override func viewDidLoad() { 
     super.viewDidLoad() 
     locationManager.delegate = self 
     locationManager.requestAlwaysAuthorization() 
     locationManager.requestWhenInUseAuthorization() 
} 

viewDidLoad()將運行並警告會出現

enter image description here

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key> 
     <string>Accessing user location to determine the nearest pickup location</string> 
     <key>NSLocationWhenInUseUsageDescription</key> 
     <string>Accessing user location to determine the nearest pickup location</string> 

的主要問題是,如果用戶點擊不允許,我該如何檢查編程?例如

// Example code snippet, not from apple officials 
if NSlocation is nil then I want to do some alert 
+0

https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423701-locationmanager – Paulw11

回答

2

如果用戶選擇拒絕定位服務您的應用程序訪問,CLLocationManager.authorizationStatus().denied(雖然你也應該注意.restricted。如果你想通知當用戶選擇是否沒有允許或拒絕您的應用程序,你可以讓自己的位置經理delegate和實施正確的方法:

class MainViewController: CLLocationManagerDelegate{ 

    let locationManager = CLLocationManager() 

    override func viewDidLoad() -> Void{ 
     super.viewDidLoad() 
     locationManager.delegate = self 
    } 

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) -> Void{ 
     switch status{ 
      case .authorizedAlways, .authorizedWhenInUse: 
       // You're allowed to use location services 
      case .denied, .restricted: 
       // You can't use location services 
      default: 
       // This case shouldn't be hit, but is necessary to prevent a compiler error 
     } 
    } 
} 
+0

非常感謝!它確實有效 – sinusGob

+0

如果您不介意,還有一個問題,我如何引導用戶進入應用程序的設置,以便用戶可以切換位置 – sinusGob

+0

https://stackoverflow.com/a/5655727/2895075 –

0

低於CLLocationManager委託方法用於檢查用戶點擊不要讓許可警報按鈕。

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { 
     switch status { 
     case .denied: 
      print("Show you own alert here") 
      break 
     } 
    } 

要位置設置重定向用戶下面如下:

  1. 添加URL類型 「首選項」 像下面的圖片 enter image description here

  2. 編寫代碼上的按鈕動作:

    UIApplication.sharedApplication().openURL(NSURL(string:"prefs:root=LOCATION_SERVICES")!)