您可以将此代码添加到 AppDelegate 的 applicationWillEnterForeground 方法中:
-(void)applicationWillEnterForeground:(UIApplication *)application {
// this method is called when staring an app that was closed / killed / never run before (after applicationDidFinishLaunchingWithOptions) and every time the app is reopened or change status from background to foreground (ex. returning from a mobile call or after the user switched to other app and then came back)
[[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
NSLog(@"AppDelegate-getDeliveredNotificationsWithCompletionHandler there were %lu notifications in notification center", (unsigned long)[notifications count]);
for (UNNotification* notification in notifications) {
NSDictionary *userInfo = notification.request.content.userInfo;
if (userInfo) {
NSLog(@"Processed a notification in getDeliveredNotificationsWithCompletionHandler, with this info: %@", userInfo);
[self showPushNotificationInAlertController:userInfo]; // this is my method to display the notification in an UIAlertController
}
}
UIApplication.sharedApplication.applicationIconBadgeNumber = 0;
}];
} }
从方法应用程序 didFinishLaunchingWithOptions: 中删除此行,如果您已将其包含在其中,因为它会清除徽章编号以及通知中心中的所有通知:
UIApplication.sharedApplication.applicationIconBadgeNumber = 0;
这目前在 iOS 12 中工作,没有机会在早期版本中进行测试。您还必须在此方法中实现代码以处理在应用程序处于前台时收到的通知:willPresentNotification:(UNNotification *)notification withCompletionHandler: 和此方法来处理用户通过点击通知打开您的应用程序的通知:didReceiveNotificationResponse: (UNNotificationResponse *) 使用CompletionHandler 响应: