当用户不允许位置时如何处理

时间:2016-10-12 12:19:42

标签: swift xcode

我目前在iPhone上玩定位服务,只用一个按钮制作一个视图控制器。

我已经为按钮创建了一个动作插座,当按下该按钮时我想要请求用户位置。

 @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")
    }
}

当用户同时按下允许和禁止时,我有办法处理吗?

1 个答案:

答案 0 :(得分:4)

当您在info.plist文件中添加NSRequestWhenInUse时,系统警报将在第一次打开应用时显示。在该警报中有两个选项“允许”和“取消”。因此,当用户点击允许时,它将进入设置,当用户启用位置时,您的应用将更新用户的位置。所以你不必随便做任何事情。

enter image description here

并添加此方法,

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: "")