为此,您需要实现该方法didChangeAuthorizationStatus
对于不久之后调用的位置管理器委托CLLocationManager
已初始化。
首先,不要忘记在文件顶部添加:import CoreLocation
为此,请在使用该位置的类中添加委托协议。然后在viewDidLoad
方法(或applicationDidFinishLaunching
如果你在AppDelegate
)初始化你的位置管理器并设置它的delegate
财产给self
:
class myCoolClass: CLLocationManagerDelegate {
var locManager: CLLocationManager!
override func viewDidLoad() {
locManager = CLLocationManager()
locManager.delegate = self
}
}
最后,在您之前声明的类的主体中实现 locationManager(_ didChangeAuthorizationStatus _) 方法,当授权状态更改时,一旦您的用户单击按钮,就会调用该方法。你可以这样实现:
private func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
// If status has not yet been determied, ask for authorization
manager.requestWhenInUseAuthorization()
break
case .authorizedWhenInUse:
// If authorized when in use
manager.startUpdatingLocation()
break
case .authorizedAlways:
// If always authorized
manager.startUpdatingLocation()
break
case .restricted:
// If restricted by e.g. parental controls. User can't enable Location Services
break
case .denied:
// If user denied your app access to Location Services, but can grant access from Settings.app
break
default:
break
}
}
Swift 4 - 新的枚举语法
对于 Swift 4,只需将每个枚举大小写的第一个字母切换为小写(.notDetermined、.authorizedWhenInUse、.authorizedAlways、.restricted 和 .denied)
这样您就可以处理每种情况,无论用户只是授予许可还是撤销许可。