小编kiu*_*iho的帖子

如何在 iOS 应用程序中强制“始终”访问位置

我正在构建的应用程序始终需要位置访问才能正常工作。该应用程序基本上跟踪位置并将其放在地图上和其他东西上(细节并不重要,哈哈)。

我的目标是这样的:

  1. 提示用户启用“始终”位置访问
  2. 如果总是请求位置访问但用户拒绝,则使应用程序无法使用 - 基本上只是显示一个小按钮,将他们重定向到可以更改该设置的设置。

我的AppDelegate.swift正在实现CLLocationManagerDelegate,代码如下:

alreadyRequestedLocationWhenInUse = UserDefaults.standard.bool(forKey: "alreadyRequestedLocationWhenInUse")
alreadyRequestedLocationAlways = UserDefaults.standard.bool(forKey: "alreadyRequestedLocationAlways")

        func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
      
        switch CLLocationManager.authorizationStatus() {
        case .notDetermined:
            if (!alreadyRequestedLocationWhenInUse) {
                print("Requesting location access 'while in use'.")
                self.locationManager.requestWhenInUseAuthorization();
                UserDefaults.standard.set(true, forKey: "alreadyRequestedLocationWhenInUse")
                alreadyRequestedLocationWhenInUse = true
            } else {
                promptToChangeLocationSettings()
            }
        case .restricted, .denied:
            print("No Location access")
            promptToChangeLocationSettings()
            break;
        case .authorizedWhenInUse:
            if (!alreadyRequestedLocationAlways) {
                print("Requesting location access 'Always'.")
                self.locationManager.requestAlwaysAuthorization()
                UserDefaults.standard.set(true, forKey: "alreadyRequestedLocationAlways")
                alreadyRequestedLocationAlways = true
            } else {
                promptToChangeLocationSettings()
            }
            break;
        case .authorizedAlways:
            self.startLocationMonitoring();
            break; …
Run Code Online (Sandbox Code Playgroud)

location cllocationmanager ios swift

5
推荐指数
1
解决办法
7851
查看次数

标签 统计

cllocationmanager ×1

ios ×1

location ×1

swift ×1