swift中按钮被按下后如何请求位置权限

wbrvyc0a  于 2023-03-11  发布在  Swift
关注(0)|答案(1)|浏览(136)

我正在使用一个需要位置数据的天气应用程序。为了获取数据,我只想在用户按下locationButton时请求权限,而不是在应用程序打开时请求权限。当我在viewDidLoad之后调用locationManagerDidChangeAuthorization方法时,它工作正常,但当我在button get pressed方法内部调用它时,它不工作。有什么解决方案吗?

@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方法中调用了授权许可请求,但它不起作用。

yqhsw0fo

yqhsw0fo1#

您不是在locationButtonPressed中调用locationManagerDidChangeAuthorization,而是在locationButtonPressed函数中声明locationManagerDidChangeAuthorization函数。该函数永远不会以这种方式使用或调用。
将该委托方法放回它所属的类的顶级。
解决方案是等待并初始化按钮处理程序中的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
     }
}

相关问题