我目前正在研究 iPhone 上的定位服务,并制作了一个只有一个按钮的 View Controller 。
我已经为按钮创建了一个 Action 导出,按下时我想请求用户位置。
@IBAction func requestLocation(_ sender: AnyObject) {
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
checkLocation()
}
我还调用了我的 checkLocation() 函数来检查它的授权状态,但是它在用户有机会允许或禁止请求之前被调用。
func checkLocation() {
if CLLocationManager.locationServicesEnabled() {
switch(CLLocationManager.authorizationStatus()) {
case .notDetermined, .restricted, .denied:
print("No access")
case .authorizedAlways, .authorizedWhenInUse:
print("Access")
}
} else {
print("Location services are not enabled")
}
}
当用户同时按下允许和禁止时,我有什么办法可以处理吗?
最佳答案
当您在 info.plist 文件中添加 NSRequestWhenInUse 时,系统警报将在应用程序第一次打开时显示。在该警报中有两个选项“允许”和“取消”。因此,当用户点击允许时,它将转到设置,当用户启用位置时,您的应用程序将更新用户的位置。因此,您不必在菜单上执行任何操作。
并添加这个方法,
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error?) {
// [manager stopUpdatingLocation];
print("error\(error)")
switch error!.code {
case kCLErrorNetwork:
// general, network-related error
var alert = UIAlertView(title: "Location Error!", message: "Can't access your current location! Please check your network connection or that you are not in airplane mode!", delegate: nil, cancelButtonTitle: "Ok", otherButtonTitles: "")
alert.show()
case kCLErrorDenied:
var alert = UIAlertView(title: "Location Error!", message: "Location Access has been denied for app name!", delegate: nil, cancelButtonTitle: "Ok", otherButtonTitles: "")
// alert.tag=500;
alert.show()
default:
var alert = UIAlertView(title: "Location Error!", message: "Can't access your current location!", delegate: nil, cancelButtonTitle: "Ok", otherButtonTitles: "")
关于swift - 用户不允许定位时如何处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39998459/