Sot*_*ras 2 permissions core-location swift
如果用户在第一次被问到时拒绝,是否有任何方法可以要求用户授予位置检测权限?
为了获取用户的当前位置,您需要声明:
let locationManager = CLLocationManager()
Run Code Online (Sandbox Code Playgroud)
在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()
}
Run Code Online (Sandbox Code Playgroud)
然后在CLLocationManagerDelegate方法中,您可以获取用户的当前位置坐标:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var locValue:CLLocationCoordinate2D = manager.location.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
Run Code Online (Sandbox Code Playgroud)
如果用户拒绝了该位置,则给他选择更改设置的位置权限的方法:
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")
}
}))
}
Run Code Online (Sandbox Code Playgroud)
注意:
确保将隐私密钥(NSLocationAlwaysAndWhenInUseUsageDescription)添加到Info.plist文件中。
| 归档时间: |
|
| 查看次数: |
5270 次 |
| 最近记录: |