asdkajd
asdkajd

Reputation: 31

ReactNative: How to check if the user has granted permission to gps

In iOS, I am checking if the app has permissions to access the gps when opening the app. If not, I show an alert to cancel or accept, which opens the settings menu. But I can't find a way to check it once the user has turned on/off the gps in the settings menu and goes back to the app. I want to wait for the user to come back from settings and check it again.

I am using navigator.geolocation.getCurrentPosition() , Permissions.request("location") and if (Permissions.canOpenSettings()){ Permissions.openSettings()...

Upvotes: 0

Views: 2492

Answers (3)

Jo Momma
Jo Momma

Reputation: 1307

If you are using Expo for your app you can call getPermissionsAsync()

If it returns false you can try to call something like this:

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
    }

If you use hooks you can call this every time the screen / component loads using the useEffect hook or perform some other logic to determine when to ask.

Upvotes: 0

asdkajd
asdkajd

Reputation: 31

I found a workaround, it doesn't check it when the user goes back, but opens an alert right when the settings window is opened so when he goes back he has to click Ok and it checks it again:

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 }
    );
  }

Upvotes: 1

P-A Bouly
P-A Bouly

Reputation: 243

You can use AppState and add a listener when the app is active again to check if the permission is denied or not.

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {
    //Check permission here
  };

Upvotes: 0

Related Questions