Swift - 未授予核心位置请求权限

时间:2016-11-25 11:27:04

标签: swift permissions core-location

有没有办法要求用户提供位置检测权限,如果他们在第一次被问到时被拒绝了?

2 个答案:

答案 0 :(得分:4)

要获取用户的当前位置,您需要声明:

let locationManager = CLLocationManager()

在viewDidLoad()中:

  // Ask for Authorisation from the User.
  self.locationManager.requestAlwaysAuthorization() 

  // For use in foreground
  self.locationManager.requestWhenInUseAuthorization()

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

然后在CLLocationManagerDelegate方法中,您可以获得用户的当前位置坐标:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    var locValue:CLLocationCoordinate2D = manager.location.coordinate
    print("locations = \(locValue.latitude) \(locValue.longitude)")
}

如果用户拒绝了该位置,则可以选择从设置中更改位置权限:

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    print("error::: \(error)")
    locationManager.stopUpdatingLocation()
    let alert = UIAlertController(title: "Settings", message: "Allow location from settings", preferredStyle: UIAlertControllerStyle.Alert)
    self.presentViewController(alert, animated: true, completion: nil)
    alert.addAction(UIAlertAction(title: TextMessages().callAlertTitle, style: .Default, handler: { action in
        switch action.style{
        case .Default: UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
        case .Cancel: print("cancel")
        case .Destructive: print("destructive")
        }
    }))
}

答案 1 :(得分:1)

不,您可以在警报内提醒他们内部应用,例如“为了更好地使用,我们建议您授予我们使用您所在位置的权限”。并添加“转到设置”按钮,将用户重定向到应用程序的位置权限。

相关问题