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

标签: Xcode Swift
发布时间: 2016/12/26 23:33:23
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我正在玩在 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:

当在 info.plist 文件中添加了 NSRequestWhenInUse 时,系统警报将显示在第一次当应用程序将打开。在该警报都有两个选项允许' 和 '取消'。所以当用户单击允许它将去到设置,当用户启用位置时,您的应用程序将更新用户的位置。所以你不必做任何事 menually。

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: "")
官方微信
官方QQ群
31647020