-->

How to receive iOS notifications in background wit

2019-08-19 08:41发布

问题:

I have use following methods to receive notifications in AppDelegate. When user is on foreground notification receives as expected. But if user is on background notification will receive(in AppDelegate) notification only if user tapped a popup. How to receive notification without involving user tap when app running on background.

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    NSLog( @"Handle push from foreground" );
    // custom code to handle push while app is in the foreground

    [[ACBRemoteNotificationManger sharedManager] addNotificationFromUNNotification:notification];
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler
{
    NSLog( @"Handle push from background or closed" );
    // if you set a member variable in didReceiveRemoteNotification, you  will know if this is from closed or background
    NSLog(@"%@", response.notification.request.content.userInfo);
} 

回答1:

If this is really your requirement to execute some method/code on receiving PUSH in background mode you have to implement application:didReceiveRemoteNotification:fetchCompletionHandler:

It is stated in Documentation

To support this background mode, enable the Remote notifications option from the Background modes section of the Capabilities tab in your Xcode project.

For a push notification to trigger a some operation, the notification’s payload must include the content-available key with its value set to 1. When that key is present, the system wakes the app in the background (or launches it into the background) and calls the app delegate’s application:didReceiveRemoteNotification:fetchCompletionHandler: method. Your implementation of that method should perform your desired tass in background.

Check this Doumentation Link too

When a remote notification arrives, the system displays the notification to the user and launches the app in the background (if needed) so that it can call this method. Launching your app in the background gives you time to process the notification and download any data associated with it, minimizing the amount of time that elapses between the arrival of the notification and displaying that data to the user.

Otherwise PUSH notification can not be handled without user interaction