我有一个实现CLLocationManagerDelegate
的视图控制器。我创建了一个CLLocationManager变量:
let locationManager = CLLocationManager()
然后在viewDidLoad
中,我设置了属性:
// Set location manager properties
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.distanceFilter = 50
问题是,即使在我检查授权状态之前,函数也会被调用。
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if (status == .AuthorizedWhenInUse) {
// User has granted autorization to location, get location
locationManager.startUpdatingLocation()
}
}
任何人都可以告诉我可能导致这种情况发生的原因吗?
答案 0 :(得分: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
}
}
请注意,您需要及时分配代表。如果你想让它发挥作用的话。
如果您以某种方式延迟委托作业,例如通过异步设置,您可能会错过对- locationManager:didChangeAuthorizationStatus:
的初始调用。
答案 1 :(得分:6)
Swift 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
}
}
答案 2 :(得分:1)
其他答案可能会引入新的不良行为。
您可以只添加一个布尔值和一个警卫以防止首次呼叫,并附上一些解释错误的注释:
var firstTimeCalled = true
// ...
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard !firstTimeCalled else {
firstTimeCalled = false
return
}
// ... send status to listeners
}