【问题标题】:Detect user selection in Location Access Popup Swift在位置访问弹出 Swift 中检测用户选择
【发布时间】:2020-01-30 07:39:11
【问题描述】:

我有一个视图控制器,它获取用户位置并显示附近的商店。

当用户第一次打开应用程序时,应用程序会显示一个弹出窗口供用户访问位置信息。如果用户允许定位,我在didUpdateLocations调用API

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if !isNearbyAlreadyLoaded {
        self.apiNearbyBakers()
        isNearbyAlreadyLoaded = true
    }
}

但如果用户不允许该位置,则永远不会调用我的 API。在这种情况下,我需要向他展示一个按钮以允许定位。

问题

如何检测用户是否点击了允许位置弹出窗口中的不允许按钮。

【问题讨论】:

    标签: ios swift cllocationmanager


    【解决方案1】:

    您可以使用didChangeAuthorization 回调方法。当用户从弹出窗口中选择一个选项时调用此方法。

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedAlways {
            if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
                if CLLocationManager.isRangingAvailable() {
                    // do stuff
                }
            }
        }
        if status == .denied {
            // handle your case
        }
    }
    

    有一篇关于这个的完整文章here

    【讨论】:

      【解决方案2】:

      为 CLLocationManagerDelegate 创建一个扩展
      然后检查状态并相应地执行您的功能,如果未设置权限,则打开设置。

      extension HomeVC: CLLocationManagerDelegate {
      
          func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
      
              guard status == .authorizedAlways || status == .authorizedWhenInUse else {
                  if status == .denied || status == .notDetermined || status == .restricted || status == .authorizedWhenInUse {
      
                      let alert = UIAlertController(title: "Title", message:"Some Descriptions" , preferredStyle: .alert)
                      alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
                      alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { _ in
                          let url = URL(string: UIApplication.openSettingsURLString)!
                          UIApplication.shared.open(url, options: [:], completionHandler: nil)
                      }))
                      self.present(alert, animated: true, completion: nil)
                  }
                  return
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-26
        • 1970-01-01
        • 1970-01-01
        • 2020-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多