react-native-background-actions icon indicating copy to clipboard operation
react-native-background-actions copied to clipboard

How to set up Geolocation correctly for iOS

Open Rubioli opened this issue 2 years ago • 0 comments

First of all, a great library 💯

Currently, I'm using geolocation to keep the iOS alive and this is how I do it:

const RunCronjob = async () => {
  const sleep = (time) => new Promise((resolve) => setTimeout(() => resolve(), time));
  const myBackgroundJob = async (taskDataArguments) => {
      const { delay } = taskDataArguments;
      await new Promise( async (resolve) => {
          for (let i = 0; BackgroundService.isRunning(); i++) {
            //run geolocation service just in IOS
            if (Platform.OS !== "android") {
              getUserGeoLocation();
            }

            await sleep(delay);
          }
      });
  };

  const options = {
      taskName: 'myCrons',
      taskTitle: 'title',
      taskDesc: 'desc',
      taskIcon: {
          name: 'ic_app_notification',
          type: 'drawable',
      },
      color: '#ff8e23',
      linkingURI: 'app://',
      parameters: {
          delay: 4 * 60 * 1000
      },
  };

  // iOS only Listen for the iOS-only expiration handler that allows you to 'clean up' shortly before the app’s remaining background time reaches 0
  if (Platform.OS !== "android") {
    BackgroundService.on('expiration', () => {
       getUserGeoLocation();
    });
  }

  
  if (!BackgroundService.isRunning()) {
    await BackgroundService.start(myBackgroundJob, options);

    await BackgroundService.updateNotification(); // Only Android, iOS will ignore this call
  }
}

const getUserGeoLocation = () => {
  Geolocation.getCurrentPosition(
    success => {
      console.log(success);
    },
    error => {
      console.log("geoError", error);
    },
    {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
  );
}

I set it inside the job runner to run it every 5 minutes. Is this the correct way of doing this?

But the issue is that in the background, I don't get anything and don't seem to run, even though I have allowed everything.

My info.plist:

	<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
	<string>1</string>
	<key>NSLocationAlwaysUsageDescription</key>
	<string>1</string>
	<key>NSLocationWhenInUseUsageDescription</key>
	<string>1</string>

Appreciate any feedback! Thanks in advance

Rubioli avatar Sep 10 '22 15:09 Rubioli