禁用位置服务后立即显示警报视图

Showing alertview as soon as location service is disabled

我正在制作一个需要启用位置服务的 iOS 应用。因此,一旦安装了我的应用程序,它就会要求用户允许定位服务。显然,很多用户按 "Don't allow" 并最终无法运行我的 iOS 应用程序。

在我的应用程序中,我输入了以下代码行:

  override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Denied {
            self.locationAlert = UIAlertView(title: "Location Services Permission Needed", message: "Location service needs to be turned on to use Peek! Please press setting button below and turn the service on!", delegate: self, cancelButtonTitle: "Settings")
            locationAlert.show()
      }
    }

    extension ViewController: UIAlertViewDelegate {
        func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
            alertView.dismissWithClickedButtonIndex(buttonIndex, animated: true)
            UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
        }
    }

问题是警报视图仅在您重新打开应用程序时显示。我希望这个 alertview 在用户安装应用程序时按 "Don't allow location service" 时立即显示。

有没有办法让这个动作发生?

您可以使用 CLLocationManagerDelegate 的委托方法:

- (void)locationManager:(CLLocationManager *)manager
didChangeAuthorizationStatus:(CLAuthorizationStatus)status

此方法告诉您位置授权的状态是否已更改

示例:

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    switch status {
    case .Denied:
        // Changed status to denied
        break;
    default:
        break;
    }
}

注意:记得把CLLocationManager的delegate设置为self!还最好检查是否尚未显示该警报视图以避免出现多个警报。