Agontuk / react-native-geolocation-service

React native geolocation service for iOS and android
https://www.npmjs.com/package/react-native-geolocation-service
MIT License
1.61k stars 292 forks source link

Unable to disable position observation in background on iOS (clearWatch is not working properly) #234

Open alessandro-bottamedi opened 3 years ago

alessandro-bottamedi commented 3 years ago

Hi, on iOS 14 I'm listening to the appstate to stop location if the app goes in the background. But it seems that with version 5.1.1 watch location remains active despite calling clearWatch (the blue location indicator is on in the background). If I call stopObserving the indicator disappears but I get the warning (Called stopObserving with existing subscriptions). With version 5.0.0 everything worked correctly.

Here my code:

  const watchId = useRef(null);

  // Effetto per watch position con app attiva
  useEffect(() => {
    if (appstate === 'active') {
      log.debug('GEOLOCATION WATCH: start watch');
      watchId.current = Geolocation.watchPosition(
        position => {
          log.info(position)
        },
        error => {
          if (error) {
            log.warn('GEOLOCATION WATCH: ' + error.code + ' | ' + error.message);
          }
        },
        {
          enableHighAccuracy: true,
          distanceFilter: 10,
          interval: 10000,
          fastestInterval: 5000,
          showLocationDialog: false,
          forceRequestLocation: false,
        }
      );
    } else {
      if (watchId.current) {
        log.debug('GEOLOCATION WATCH: stop watch');
        Geolocation.clearWatch(watchId.current);
        watchId.current = null;
      }
    }
    return () => {
      if (watchId.current) {
        log.debug('GEOLOCATION WATCH: stop watch');
        Geolocation.clearWatch(watchId.current);
        watchId.current = null;
      }
    };
  }, [appstate]);

What i'm doing wrong?

Agontuk commented 3 years ago

There's no subscription related changes in 5.1.1, just a new property was added for accuracy control. It's probably some kind of bug in app side as far as I can tell. The code you provided looks ok, so please check the other parts of the code.

Almouro commented 3 years ago

Hi @alessandro-bottamedi ,

Had a similar issue, the problem for me was that watchId.current can be equal to 0 and thus would be falsy

peterchijioke commented 5 months ago

Try this....

console.log('stop')

try { store.dispatch(setMountTimer(false)) // Geolocation.clearWatch(store.getState().app.watchId); Geolocation.stopObserving() showToast('Navigation was stopped','success') } catch (error) { console.log(error) }