You have to do a few things to manage the push notifications received when the application is in the background.
Firstly, on your server side you should set {"aps":{"content-available": 1.../$body['aps']['content-available'] =1; in the useful data of push notifications.
Secondly, in your Xcode project you need to provide "remote notifications." This is done by going to the project goal → features, then turning on the features switch and checking the remote notifications flag.
Thirdly, instead of using didReceiveRemoteNotification you should call application:didReceiveRemoteNotification:fetchCompletionHandler: this will allow you to perform the tasks that you want in the background at the time you receive the notification:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { if(application.applicationState == UIApplicationStateInactive) { NSLog(@"Inactive - the user has tapped in the notification when app was closed or in background"); //do some tasks [self manageRemoteNotification:userInfo]; completionHandler(UIBackgroundFetchResultNewData); } else if (application.applicationState == UIApplicationStateBackground) { NSLog(@"application Background - notification has arrived when app was in background"); NSString* contentAvailable = [NSString stringWithFormat:@"%@", [[userInfo valueForKey:@"aps"] valueForKey:@"content-available"]]; if([contentAvailable isEqualToString:@"1"]) { // do tasks [self manageRemoteNotification:userInfo]; NSLog(@"content-available is equal to 1"); completionHandler(UIBackgroundFetchResultNewData); } } else { NSLog(@"application Active - notication has arrived while app was opened"); //Show an in-app banner //do tasks [self manageRemoteNotification:userInfo]; completionHandler(UIBackgroundFetchResultNewData); } }
Finally, you should add this type of notification: UIRemoteNotificationTypeNewsstandContentAvailability to the notification settings when it is installed.
In addition, if your application was closed when a notification arrived, you should manage it in didFinishLaunchingWithOptions , and only if the user clicks on the push notification: a way to do this:
if (launchOptions != nil) { NSDictionary *dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]; if (dictionary != nil) { NSLog(@"Launched from push notification: %@", dictionary); [self manageRemoteNotification:dictionary]; } }
LaunchOptions parameter matters! = nil, when you launch the application by clicking on the push notification, if you get access to it by clicking on the icon, launchOptions will == nil.
Hope this will be helpful. This is explained by Apple .
AlbertoC Jan 15 '16 at 13:28 2016-01-15 13:28
source share