transistorsoft / react-native-background-fetch

Periodic callbacks in the background for both IOS and Android
MIT License
1.43k stars 191 forks source link

React Native IOS Background fetch is not working after Impelementing all the steps #467

Closed jamalalisubhani closed 7 months ago

jamalalisubhani commented 7 months ago

Background-fetch for updating location in background app is in killed state:

service.ts

import BackgroundFetch from 'react-native-background-fetch'; import BackgroundGeolocation from 'react-native-background-geolocation'; import { UpdateUserData } from './general.service'; import { store } from '../redux/store'; import { setAuthToken, setUser } from '../redux/reducers/userReducers';

const configureBackgroundFetch = async () => {

// Configure background fetch BackgroundFetch.configure( { minimumFetchInterval: 15, // Minimum fetch interval in minutes (e.g., 15 minutes) stopOnTerminate: false, // Continue running background fetch when the app is terminated startOnBoot: true, // Start background fetch on device boot enableHeadless: true, // Enable headless mode for background task requiresDeviceIdle: false, // Set to true to require the device to be idle forceAlarmManager: false, // Android-only: use AlarmManager instead of JobScheduler }, async (taskId) => { console.log('[BackgroundFetch] Received event:', taskId);

  // Fetch location data using BackgroundGeolocation
  BackgroundGeolocation.getCurrentPosition({
    timeout: 30,
    maximumAge: 5000,
    desiredAccuracy: 1,
  })
    .then((res) => {
      console.log('Location data:', res.coords.latitude, res.coords.longitude);

      const params = {
        longitude: res.coords.longitude,
        latitude: res.coords.latitude,
        address: 'Test background FN',
      };

      // Make your HTTP POST request here
      UpdateUserData(params)
        .then((res) => {
          // Handle the response as needed
        })
        .catch((err) => {
          if (err.response && err.response.status === 403) {
            store.dispatch(setAuthToken(null));
            store.dispatch(setUser(null));
          }
          // Handle other errors
        });

      // Finish the background fetch task
      BackgroundFetch.finish(taskId);
    })
    .catch((error) => {
      console.error('Error fetching location:', error);
      // Handle location-related errors
    });
},
async (taskId) => {  // <-- Event timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  console.log("[BackgroundFetch] TIMEOUT taskId:", taskId);
  BackgroundFetch.finish(taskId);
});
// (taskId)=>{
//   BackgroundFetch.stop(taskId);
// }

BackgroundGeolocation.start();

// Start the background fetch service BackgroundFetch.start();

// Configure and start BackgroundGeolocation BackgroundGeolocation.ready({ desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, distanceFilter: 1, stopTimeout: 50000, debug: true, logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE, stopOnTerminate: false, startOnBoot: true, }).then((state) => { console.log('- BackgroundGeolocation is configured and ready:', state);

BackgroundGeolocation.getCurrentPosition({
  timeout: 30,
  maximumAge: 5000,
  desiredAccuracy: 1,
})
  .then((res) => {
    console.log('Location data:', res.coords.latitude, res.coords.longitude);

    const params = {
      longitude: res.coords.longitude,
      latitude: res.coords.latitude,
      address: 'Test background FN',
    };

    // Make your HTTP POST request here
    UpdateUserData(params)
      .then((res) => {
        // Handle the response as needed
      })
    // Finish the background fetch task

  })
  .catch((error) => {
    console.error('Error fetching location:', error);
    // Handle location-related errors
  });

});

BackgroundGeolocation.getCurrentPosition({ timeout: 30, maximumAge: 5000, desiredAccuracy: 1, }) .then((res) => { console.log('Location data:', res.coords.latitude, res.coords.longitude);

  const params = {
    longitude: res.coords.longitude,
    latitude: res.coords.latitude,
    address: 'Test background FN',
  };

  // Make your HTTP POST request here
  UpdateUserData(params)
    .then((res) => {
      // Handle the response as needed
    })
  // Finish the background fetch task

})
.catch((error) => {
  console.error('Error fetching location:', error);
  // Handle location-related errors
});

BackgroundFetch.scheduleTask({
  taskId: "com.transistorsoft.customtask",
  delay: 5000,       // milliseconds
  forceAlarmManager: true,
  periodic: false,
  stopOnTerminate: false,
  enableHeadless: true,
});

};

export default configureBackgroundFetch;

This file is fetching background location but not calling the api for updating it in ios, what could be the possible reason, i have followed all the steps mentioned in package documnetation for configuration.

christocracy commented 7 months ago

if the actual fetch event fires and BackgroundGeolocation.getCurrentPosition returns a location, then the plugins' job is complete.

I suggest you provide BackgroundGeolocation an url to your server and let is pure-native HTTP service handle uploading to your server.

jamalalisubhani commented 7 months ago

@christocracy I am making POST api call using axios in react native ios app, its not making any api call, how can i test that?

christocracy commented 7 months ago

I have no experience with Axios. I have no need for it. The plug-in has its own built-in native http service which does not have problems running in the background. Apparently this "Axios" has problems.

If you want to use Axios for http, seek support with them.

jamalalisubhani commented 7 months ago

@christocracy thanks for the solution it worked with pure-native HTTP service handle uploading to my server.