当用户在MainViewController
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
}
viewDidLoad()
将会运行并显示警告
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Accessing user location to determine the nearest pickup location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Accessing user location to determine the nearest pickup location</string>
主要问题是,如果用户点击“不允许”,我该如何检查?例如
// Example code snippet, not from apple officials
if NSlocation is nil then I want to do some alert
答案 0 :(得分:2)
如果用户选择拒绝您的应用访问位置服务,则CLLocationManager.authorizationStatus()
将为.denied
(但您也应注意.restricted
。如果您希望收到通知当用户选择是否允许或拒绝您的应用时,您可以自己做位置管理员delegate
并实施正确的方法:
class MainViewController: CLLocationManagerDelegate{
let locationManager = CLLocationManager()
override func viewDidLoad() -> Void{
super.viewDidLoad()
locationManager.delegate = self
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) -> Void{
switch status{
case .authorizedAlways, .authorizedWhenInUse:
// You're allowed to use location services
case .denied, .restricted:
// You can't use location services
default:
// This case shouldn't be hit, but is necessary to prevent a compiler error
}
}
}
答案 1 :(得分:0)
使用CLLocationManager
下面的委托方法检查用户在权限提醒中点击不允许按钮。
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .denied:
print("Show you own alert here")
break
}
}
要在位置设置中重定向用户,请按照以下步骤操作: