Mik*_*ker 26 cllocationmanager ios swift
我有一个实现的视图控制器CLLocationManagerDelegate.我创建了一个CLLocationManager变量:
let locationManager = CLLocationManager()
Run Code Online (Sandbox Code Playgroud)
然后在viewDidLoad,我设置属性:
// Set location manager properties
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.distanceFilter = 50
Run Code Online (Sandbox Code Playgroud)
问题是,即使在我检查授权状态之前,函数也会被调用.
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if (status == .AuthorizedWhenInUse) {
// User has granted autorization to location, get location
locationManager.startUpdatingLocation()
}
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我可能导致这种情况发生的原因?
Bar*_*che 48
- locationManager:didChangeAuthorizationStatus:在CLLocationManager初始化后不久被调用.
如果需要,您可以在委托方法中请求授权:
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .NotDetermined:
locationManager.requestAlwaysAuthorization()
break
case .AuthorizedWhenInUse:
locationManager.startUpdatingLocation()
break
case .AuthorizedAlways:
locationManager.startUpdatingLocation()
break
case .Restricted:
// restricted by e.g. parental controls. User can't enable Location Services
break
case .Denied:
// user denied your app access to Location Services, but can grant access from Settings.app
break
default:
break
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您希望这样做,您需要在"及时"的情况下分配代表.
如果你以某种方式延迟代理分配,例如通过异步设置,你可能会错过初始调用- locationManager:didChangeAuthorizationStatus:.
斯威夫特3
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
manager.requestAlwaysAuthorization()
break
case .authorizedWhenInUse:
manager.startUpdatingLocation()
break
case .authorizedAlways:
manager.startUpdatingLocation()
break
case .restricted:
// restricted by e.g. parental controls. User can't enable Location Services
break
case .denied:
// user denied your app access to Location Services, but can grant access from Settings.app
break
}
}
Run Code Online (Sandbox Code Playgroud)