transistorsoft / react-native-background-fetch

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

BackgroundFetch work successfully , but I have question #IOS #466

Closed youbirox closed 1 month ago

youbirox commented 7 months ago

Your Environment

Expected Behavior

It works well periodically, sometimes every 15 minutes, sometimes 1 hour, sometimes it stops.

but I have a question, is it normal to stop working after one day? , I test on testflight. or will I have to push it to the app store

Actual Behavior

Context

In app.js :

useEffect(() => {
    initBackgroundFetch()
    //loadEvents();
  }, []);

 /// Configure BackgroundFetch.
  ///
  const initBackgroundFetch = async () => {

      await BackgroundFetch.configure({
      minimumFetchInterval: 15,      // <-- minutes (15 is minimum allowed)
      // stopOnTerminate: false,
       enableHeadless: true,
       startOnBoot: true,
    //   // Android options
    //   forceAlarmManager: false,      // <-- Set true to bypass JobScheduler.
    //  // requiredNetworkType: BackgroundFetch.NETWORK_TYPE_ANY, // Default
    //   requiresCharging: false,       // Default
    //   requiresDeviceIdle: false,     // Default
    //   requiresBatteryNotLow: false,  // Default
    //   requiresStorageNotLow: false,  // Default
    }, async (taskId) => {

      const value = await AsyncStorage.getItem('userInfo')
      if (value) {
        const data = JSON.parse(value);
        const token = data.token
        await axios.get(`${BASE_TEST}`,
        {
          headers: {
            "Access-Control-Allow-Origin": "*",
            "Content-type": "Application/json",
            "Authorization": `Bearer ${token}`
          }
        })
        .then(function (response) {

         //console.log(response.data)
         let DataV = response.data['Harvest']

          const summedCATodayAPINew = DataV?.reduce((a, v) => a = a + v.CA, 0);

          const  widgetDataN = {

           TitleCA: 'Harvest',
           CA: parseInt(summedCATodayAPINew)+'€',

         };
          SharedGroupPreferences.setItem('widgetKey', widgetDataN, group);

          console.log(summedCATodayAPINew)
          //         PushNotificationIOS.presentLocalNotification({
          //    alertTitle : 'Background Fetch',
          //    alertBody : String(summedCATodayAPINew)+'€',
          //  })

       // DO BACKGROUND WORK HERE

       // This MUST be called in order to signal to the OS that your task is complete
       BackgroundFetch.finish(taskId)
        })
      }else
      {
        console.log('User token not found , Background fetch will be refresh after time')
       // DO BACKGROUND WORK HERE

       // This MUST be called in order to signal to the OS that your task is complete
       BackgroundFetch.finish(taskId)
      }

    }, (error) => {
      console.log("[js] RNBackgroundFetch failed to start");
      BackgroundFetch.finish(taskId)
    });
    BackgroundFetch.start();

  }

Debug logs

ashishmangukiya commented 7 months ago

@youbirox I really need your help if you can... I have already raised a issue -> Github issue I have configured everything as per the doc available in the library also installed the demo app which is attached to the library but I am not able to get any events in my app or demo app. Have you faced any issue while integrating the library ? Can you check my code which is there in the issue? if you find any issue in my code then plz reply.

youbirox commented 7 months ago

@ashishmangukiya yes , I can check your code .

hoanglinh194 commented 1 month ago

sure not working on IOS real device ,

hoanglinh194 commented 1 month ago

version 4.2.3

hoanglinh194 commented 1 month ago

import moment from 'moment'; import BackgroundFetch from '../helpers/rnbackgroundfetch' import { setTimeStamp } from '../redux-toolkit/reducer'; import { store } from '../redux-toolkit/store'; export const initBGTaskSchedule = async () => { // Step 1: Configure BackgroundFetch as usual. await BackgroundFetch.configure({ minimumFetchInterval: 15 }, async (taskId) => { // <-- Event callback // This is the fetch-event callback. // Use a switch statement to route task-handling. switch (taskId) { case 'com.transistorsoft.customtask': store?.dispatch(setTimeStamp(moment().milliseconds())) break; default: break } // Finish, providing received taskId. BackgroundFetch.finish(taskId); }, async (taskId) => { // <-- Task timeout callback // This task has exceeded its allowed running-time. // You must stop what you're doing and immediately .finish(taskId) BackgroundFetch.finish(taskId); }); }

export const scheduleTask = async () => { // Step 2: Schedule a custom "oneshot" task "com.foo.customtask" to execute 5000ms from now. await BackgroundFetch.scheduleTask({ taskId: "com.transistorsoft.customtask", forceAlarmManager: true, delay: 5000 // <-- milliseconds }); }

christocracy commented 1 month ago

but I have a question, is it normal to stop working after one day?

Yes, if you don't periodically open the app, the iOS background-fetch algorithm will halt firing events.