2016-05-16 50 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

这在我的情况下是正确的!谢谢! –

相关问题