transistorsoft / capacitor-background-fetch

Periodic callbacks in the background for both IOS and Android
78 stars 9 forks source link

Javascript should be executed in the background #25

Closed Caperious closed 3 months ago

Caperious commented 3 months ago

Your Environment

Installed Dependencies:

@capacitor/cli: 6.0.0 @capacitor/core: 6.0.0 @capacitor/android: 6.0.0 @capacitor/ios: 6.0.0

export const EventCalendarSyncHook = () => {
  useEffect(() => {
    // fetchAndSyncEvents();
    const isWeb = !(isPlatform("ios") || isPlatform("android"));
    if (isWeb) {
      console.log("Not running on mobile device, skipping background fetch initialization");
      return;
    }
    initBackgroundFetch().catch((err) => {
      console.error("Error while initializing background fetch", err);
    });
  }, []);
};

const initBackgroundFetch = async () => {
  const status = await BackgroundFetch.configure(
    {
      minimumFetchInterval: 15,
      requiredNetworkType: BackgroundFetch.NETWORK_TYPE_ANY,
    },
    async (taskId) => {
      console.log("[BackgroundFetch] EVENT:", taskId);
      // Perform your work in an awaited Promise
      try {
        const result = await fetchAndSyncEvents();
        console.log("[BackgroundFetch] work complete:", result);
      } catch (e) {
        console.error("[BackgroundFetch] Error occurred while fetching and syncing events", e);
      }
      // [REQUIRED] Signal to the OS that your work is complete.
      BackgroundFetch.finish(taskId);
    },
    async (taskId) => {
      // The OS has signalled that your remaining background-time has expired.
      // You must immediately complete your work and signal #finish.
      console.log("[BackgroundFetch] TIMEOUT:", taskId);
      // [REQUIRED] Signal to the OS that your work is complete.
      BackgroundFetch.finish(taskId);
    }
  );

  // Checking BackgroundFetch status:
  if (status !== BackgroundFetch.STATUS_AVAILABLE) {
    // Uh-oh:  we have a problem:
    if (status === BackgroundFetch.STATUS_DENIED) {
      alert("The user explicitly disabled background behavior for this app or for the whole system.");
    } else if (status === BackgroundFetch.STATUS_RESTRICTED) {
      alert("Background updates are unavailable and the user cannot enable them again.");
    }
  }
}; 

Context

Im trying to fetch data from the api, and sync the data into the calendar.

Debug logs

christocracy commented 3 months ago

It's likely due to the Capacitor WebView shutting down.

Try setting useLegacyBridge in your capacitor.config.ts:

const config: CapacitorConfig = {
  .
  .
  .
  android: {
    useLegacyBridge: true
  }
};
Caperious commented 3 months ago

That did the trick. Thanks for the quick response.

Caperious commented 3 months ago

Hi @christocracy ,

I actually have a similar issue on the Ios as well. There the code starts executing (i can see the console logs), but when i get to the fetching from storage, the code stops executing. If i let it "hang", timeout is executed. If i bring the app to the foreground in the meantime, the code executes as it should.

Is there a similar trick for Ios as the one above, or do i have a problem with @ionic/storage?

christocracy commented 3 months ago

Post your code.

Caperious commented 3 months ago

I have figured it out. The problem was @ionic/storage. I used @capacitor/preferences instead to retreive required information from storage. Thank you for your inquiry though.