【问题标题】:ReactNative: How to check if the user has granted permission to gpsReactNative:如何检查用户是否已授予 gps 权限
【发布时间】:2019-04-25 11:57:09
【问题描述】:

在 iOS 中,我在打开应用程序时检查应用程序是否有权访问 GPS。如果没有,我会显示取消或接受的警报,这会打开设置菜单。但是一旦用户在设置菜单中打开/关闭 gps 并返回应用程序,我就找不到检查它的方法。 我想等待用户从设置中返回并再次检查。

我正在使用 navigator.geolocation.getCurrentPosition()Permissions.request("location")if (Permissions.canOpenSettings()){ Permissions.openSettings()...

【问题讨论】:

    标签: ios reactjs geolocation gps native


    【解决方案1】:

    我找到了一种解决方法,当用户返回时它不会检查它,但会在打开设置窗口时打开一个警报,所以当他返回时他必须单击“确定”并再次检查:

    componentDidMount() {
        this.checkPermissions();
      }
    
    checkPermissions(){
        Permissions.check("location").then(resp => { // if resp === "denied" alert to open settings }
    }
    
    openSettings(){if (Permissions.canOpenSettings()) {
          Permissions.openSettings().then(this.renderReloadAlert());
        }}
    
    renderReloadAlert() {
        const s = strings.initial;
        Alert.alert(
          s.alertReloadTitle,
          s.alertReloadBody,
          [
            {
              text: s.alertReloadOk,
              onPress: () => this.checkPermissions()
            }
          ],
          { cancelable: false }
        );
      }
    

    【讨论】:

      【解决方案2】:

      您可以使用 AppState 并在应用再次处于活动状态时添加侦听器以检查权限是否被拒绝。

        componentDidMount() {
          AppState.addEventListener('change', this._handleAppStateChange);
        }
      
        componentWillUnmount() {
          AppState.removeEventListener('change', this._handleAppStateChange);
        }
      
        _handleAppStateChange = (nextAppState) => {
          //Check permission here
        };
      

      【讨论】:

      • 我发现在某些情况下请求权限会将状态设置为后台状态,这会导致循环
      【解决方案3】:

      如果您的应用使用 Expo,您可以致电 getPermissionsAsync()

      如果它返回 false,你可以尝试这样调用:

      const checkForLocationPermission = async () => {
              const result = await getPermissionsAsync();
              if (result.status === 'granted'){
                  return true
              } else {
                  const response = requestPermissionsAsync();
                  if (response.status === 'granted'){
                      return true;
                  }
              }
              return false
          }
      

      如果您使用钩子,您可以在每次屏幕/组件加载时使用 useEffect 钩子调用它,或者执行一些其他逻辑来确定何时询问。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多