Get push id when app is in background state iOS

Viewed 29

I need to store the identifier of a push that came in remotely. If the application is in the foreground, the willPresentNotification method fires and I can easily take the push id from notification.request.identifier. However, when the push comes to the application in the background state, didReceiveRemoteNotification fires, but it does not give me this push ID. Help, where can I get a specific ID of a specific push?

1 Answers

As stated here: https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/1649520-getdeliverednotifications , the UNUserNotificationCenter class provides a method, getDeliveredNotificationsWithCompletionHandler:, to get all your app's notifications that are in the notification center.

The notification that arrives and displays when your app is in the background is also in there, and its the first object in this array since its the top most notification received.

Forgive the objective-c code, but here's an example:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler{

   UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
   [center getDeliveredNotificationsWithCompletionHandler:^(NSArray *notifications){
        
     UNNotification *lastReceivedNotification = [notifications firstObject];
     NSString *identifier = [[lastReceivedNotification request] identifier];
     // do something
    
   }];

   //...

}
Related