Avijit Nagare Avijit Nagare - 5 months ago 50
Objective-C Question

Notification action background fetch in iOS?

I used this code to awake app from close to background in push notification as

UIMutableUserNotificationAction *action2;
action2 = [[UIMutableUserNotificationAction alloc] init];
[action2 setActivationMode:UIUserNotificationActivationModeBackground];////UIUserNotificationActivationModeBackground
[action2 setTitle:@"ACCEPT"];
[action2 setIdentifier:NotificationActionTwoIdent];
[action2 setDestructive:NO];
[action2 setAuthenticationRequired:NO];


Now i am hitting web service in following method
//Remote Notificaiton

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
//Call to web services.


//show local notification in background

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil)
{
return;
}
else
{
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:60];
localNotification.alertAction = nil;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = [NSString stringWithFormat:@"Worked=> %@",jsonArray];
localNotification.alertAction = NSLocalizedString(@"Read Msg", nil);
localNotification.applicationIconBadgeNumber=1;
localNotification.repeatInterval=0;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}


}


I enabled background fetch in app. My Questions are


  1. I am using NSURLConnetion class for network call. it works sometime but not seems to other time.

  2. Notification alert not showing in background.

  3. Do i need to use performFetchWithCompletionHandler completionHandler delegate?
    Any one could help me to fix this? thanks in advance.


Answer

I implemented like this :

- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier
completionHandler:(void (^)())completionHandler {
        self.backgroundSessionCompletionHandler = completionHandler;

        //add notification
        [self presentNotification];
}

-(void)presentNotification{
        UILocalNotification* localNotification = [[UILocalNotification alloc] init];
        localNotification.alertBody = @"Upload Complete!";
        localNotification.alertAction = @"Background Transfer Upload!";

        //On sound
        localNotification.soundName = UILocalNotificationDefaultSoundName;

        //increase the badge number of application plus 1
        localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;

        [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}