Ionic React Track users live location while ios app is in background

128 Views Asked by At

I am native iOS Developer who is trying ionic react programming for very first time. I am doing POC to track ios device's location while app is in background. But I am struuggling to achive that since two days. Could anybody please help me to do that?

As per ionic react documentation we need to use @capacitor/geolocation to implement location tracking feature. I read the documentation and I found that watchPosition(options: PositionOptions, callback: WatchPositionCallback) => Promise<CallbackID> this method to be used to track live location of device.

Please refer below code

Code I am using to get the user's permission to track the location which is working fine.

const requestPermission = async () => {
  try {
    const result = await Geolocation.requestPermissions();
    if (result.location === 'granted') {
      console.log('Permission granted');
    } else {
      // Handle denied permission
    }
  } catch (error) {
    console.error('Error requesting location permission:', error);
  }
}

Code I am using to track user's location in background

const startBackgroundTracking = async () => {
  console.log('startBackgroundTracking');
  const watchId = Geolocation.watchPosition(
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 5000,
      // Other options...
    },
    (position: Position | null, error: any) => {
      console.log('(position: Position | null, error: any) =>', position, error)

      if (position) {
        console.log('Background position:', position.coords.latitude, position.coords.longitude);
        // Send location updates to server or perform desired actions
      } else if (error) {
        console.error('Error watching position:', error);
      }
    }
  );

Please not that live tracking of the user's device is performing well I am facing issue with live tracking while app goes in background state.

Also I have added required keys in Info.plist in Xcode project -

  • NSLocationAlwaysUsageDescription (Privacy - Location Always Usage Description)
  • NSLocationWhenInUseUsageDescription (Privacy - Location When In Use Usage Description)

Also I have enabled background location updates capability in Xcode projectEnabled Backgroud location updates capabilty

Any help would be appreciated! Thanks in advance.

0

There are 0 best solutions below