I have been trying to get Background Fetch on iOS for a few weeks now but with no luck. I followed the steps in the docs correctly but have been unable to get it to run on iOS. I am including a snippet of my code below, if anyone could point out my issue it would be greatly appreciated.
startBackgroundTask below is called from the global scope in app.js
const startBackgroundTask = async () => {
TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
console.log('BackgroundTask running');
try {
// I am making a console.log and then calling an API here
return BackgroundFetch.Result.NewData;
} catch (err) {
console.log(`Error occured while running task: ${err.message}`, err);
return BackgroundFetch.Result.Failed;
}
});
const status = await BackgroundFetch.getStatusAsync();
if (status === BackgroundFetch.Status.Restricted || status === BackgroundFetch.Status.Denied) {
console.log('Background fetch is disabled.');
return;
}
try {
await BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, {
minimumInterval: INTERVAL,
stopOnTerminate: true,
startOnBoot: false,
});
await BackgroundFetch.setMinimumIntervalAsync(INTERVAL);
console.log('Background update task registered.');
} catch (err) {
console.log('Filed to register task for background.', err);
}
}
Result:
Console.log never prints and the task is never executed.
So yesterday I tried cloning the expo example apps repo:
It has a BackgroundFetchScreen that has what I need and I was not able to get it to work either. the screen always stays at “There was no BackgroundFetch call yet.”
I tried to do an expo build:ios for simulator but the experiment doesn’t even show notifications when I drag and drop the app into the simulator. The permissions dialog does not show up while on managed
I did a few other experiments one of them is to eject the app. This made the notifications work again. But the background task still does not fire.
However, the weird part is sometimes at random times during the day it does get “triggered” the thing is I can’t find a proper pattern. I know its not supposed to be predictable to the second but I can’t even tell the frequency per hour is more than 0.
Awesome @trajano!!! Thank you for your reply. I will definitely try the example out. Were you able to trigger a local notification from the background fetch?