2016-05-16 33 views
1

我正在嘗試定位服務應用程序,因此當用戶轉到該視圖控制器時,他將獲得獲取當前位置的警報。如何知道用戶是否拒絕了Swift 2中的定位服務

這是代碼

override func viewDidLoad() { 
     super.viewDidLoad() 
// 1. status is not determined 
     if CLLocationManager.authorizationStatus() == .NotDetermined { 
      locationManager.requestAlwaysAuthorization() 
     } 
      // 2. authorization were denied 
     else if CLLocationManager.authorizationStatus() == .Denied { 



      SwiftSpinner.hide() 
      let alert = UIAlertController(title: "Error with Your Location" , message: "Location services were previously denied. Please enable location services for this app in Settings.", preferredStyle: UIAlertControllerStyle.Alert) 
      let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { 
       UIAlertAction in 
       UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) 


      } 
      alert.addAction(ok) 
      let cancel = UIAlertAction(title: "Back", style: UIAlertActionStyle.Default) { 
       UIAlertAction in 

       self.movenav("arxiki") 

      } 
      alert.addAction(cancel) 
      self.presentViewController(alert, animated: true, completion: nil) 

     } 
      // 3. we do have authorization 
     else if CLLocationManager.authorizationStatus() == .AuthorizedAlways { 
      locationManager.startUpdatingLocation() 
     } 


     self.navigationController?.setNavigationBarHidden(false, animated: true) 

     self.eventsTable.backgroundColor = UIColor.lightGrayColor() 

     // self.locationManager.requestAlwaysAuthorization() 

     if CLLocationManager.locationServicesEnabled() { 
      locationManager.delegate = self 
      locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
      locationManager.startUpdatingLocation() 
     } 

    } 

我的問題如下。 如果用戶按下「不授權」我如何得到他的選擇,以便我可以將他發回給以前的視圖控制器或警告他我留下的消息?

回答

3

爲了捕獲用戶選擇,您需要聲明CLLocationManager對象並實現其委託(CLLocationManagerDelegate)並使用以下方法捕獲它。

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { 
    if status == .Denied || status == .NotDetermined{ 
     // User selected Not authorized 
    }  
} 

我假設你已經配置了info.plist和合適的位置參數。

希望它有幫助!

+0

這在我的情況下是正確的!謝謝! –

相關問題