快速按下按钮时如何请求位置权限

问题描述 投票:0回答:1

我正在开发一个需要位置数据的天气应用程序。要获取数据,我只想在用户按下 locationButton 时请求权限,而不是在应用程序打开时请求权限。 当我在 viewDidLoad 之后调用

locationManagerDidChangeAuthorization
方法时它工作正常但是当我在按钮按下方法中调用它时它不起作用。有什么解决办法吗?

@IBAction func locationButtonPressed(_ sender: UIButton) {
     
     func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
         if #available(iOS 14.0, *) {
             switch manager.authorizationStatus {
             case .authorizedWhenInUse:  // Location services are available.
                 
                 break
                 
             case .restricted, .denied:  // Location services currently unavailable.
                
                 break
                 
             case .notDetermined:        // Authorization not determined yet.
                 manager.requestWhenInUseAuthorization()
                 break
                 
             default:
                 break
             }
         } else {
             // Fallback on earlier versions
         }
     }
 }

我在 locationButtonPressed 方法中调用了授权许可请求,但它不起作用。

ios swift core-location
1个回答
0
投票

您不是在

locationManagerDidChangeAuthorization
内部调用
locationButtonPressed
,而是在
locationManagerDidChangeAuthorization
函数内部声明
locationButtonPressed
函数。该函数将永远不会以这种方式使用或调用。

将该委托方法放回到它所属的类的顶层。

您需要的解决方案是在按钮处理程序中等待并初始化

CLLocationManager
的实例。这将延迟对用户的任何提示,直到他们点击按钮之后。

你的代码看起来像这样:

class SomeViewController: UIViewController {
    var locationManager: CLLocationManager?

    @IBAction func locationButtonPressed(_ sender: UIButton) {
        if locationManager == nil {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            // locationManagerDidChangeAuthorization will now be called automatically
        }
    }
}

extension SomeViewController: CLLocationManagerDelegate {
     func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
         if #available(iOS 14.0, *) {
             switch manager.authorizationStatus {
             case .authorizedWhenInUse:  // Location services are available.
                 // Begin getting location updates
                 manager.startUpdatingLocation()
             case .restricted, .denied:  // Location services currently unavailable.
                 break
             case .notDetermined:        // Authorization not determined yet.
                 manager.requestWhenInUseAuthorization()
             default:
                 break
             }
         } else {
             // Fallback on earlier versions
         }
     }

     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
         // handle location as needed
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.