I'm new to iOS. I have googled a lot for this question, tried many approaches and finally, I'm here.
In my application, I have to push a notification in the background when a new record is found in the API response. As per Apple documentation, I have implemented performFetchWithCompletionHandler
as below:
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//User Login status from NSUserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL Is_User_Logged_in = [defaults boolForKey:IS_USER_LOGGED_IN];
if(Is_User_Logged_in){
NSLog(@"background fetch started");
//fetchDataFromAPIs method calls 3 API's here
// and if a new record found, inserts into the local sqlitedb
if([self fetchDataFromAPIs])
{
//getUpdatedInfo method checks the new record in the local sqlitedb
// and fires a notification
if([self getUpdatedInfo])
{
NSLog(@"Content Uploaded and pushed notification");
completionHandler(UIBackgroundFetchResultNewData);
[[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_HOME object:self];
NSLog(@"Time: %@", [Constants getCurrentTimeStamp]);
}
else{
completionHandler(UIBackgroundFetchResultNoData);
NSLog(@"Time: %@", [Constants getCurrentTimeStamp]);
}
}
}
}
The above method fires the notification when the app is in the background but when the app is terminated nothing is happening. Fetch time interval is unpredictable.
I have set minimum time interval to perform background fetch in the application delegate method as below:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
[self registerForRemoteNotifications];
return YES;
}
How to make performFetchWithCompletionHandler
to run in the background for certain regular time intervals without fail?
How to run performFetchWithCompletionHandler
when the app is terminated by the user?
Also, I'm running an NSTimer with a regular time interval in the foreground of the app to show the updates as badge number and a notification as shown below:
self.timer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(UpdatePages) userInfo:nil repeats:YES];
As I already implemented performFetchWithCompletionHandler
in the application delegate, should I skip this NSTimer
in the foreground?
Please help to sort this. Many thanks in advance.