应用程序在后台时无法删除通知

时间:2019-08-20 10:04:24

标签: ios objective-c push-notification

嗨,我正在尝试在我的应用程序处于后台并且无提示推送到达时从通知中心删除通知。如果该应用程序位于Foreground或已连接到调试器,则效果很好。

但是,当应用程序在后台运行时,它不起作用。我在removeDeliveredNotificationsWithIdentifiers内的didReceiveRemoteNotification中使用。有什么建议吗? 谢谢

[center getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {

   for (UNNotification* notification in notifications) 
   {
         NSDictionary* ui = notification.request.content.userInfo;

         if ([ui[@"activityId"] isEqualToString:activityId]) 
         {            
             [center removeDeliveredNotificationsWithIdentifiers:@[notification.request.identifier]];
         }

    }
    completionHandler(UIBackgroundFetchResultNoData);                     
}]; 

2 个答案:

答案 0 :(得分:0)

尝试使用UIApplicationState属性。

示例:

  UIApplicationState* applicationState;
  if (applicationState == UIApplicationStateActive) {
    // Application is running in foreground
    //Handler 
   }
   else if (applicationState == UIApplicationStateBackground || applicationState == UIApplicationStateInactive) {
   // Application is brought from background or launched after terminated
   // Handler 
   }

答案 1 :(得分:0)

“无效”是什么意思?没有调用didReceiveRemoteNotification,还是removeDeliveredNotificationsWithIdentifiers不起作用?

有两种didReceiveRemoteNotification方法,其中一种已弃用。

application:didReceiveRemoteNotification :(不建议使用) 应用程序:didReceiveRemoteNotification:fetchCompletionHandler:

在Apple文档中:

Unlike the application:didReceiveRemoteNotification: method, 
which is called only when your app is running in the foreground, 
the system calls this method when your app is running in the foreground or background. 

或者您可以尝试: userNotificationCenter:willPresentNotification:withCompletionHandler:(Apple重新命令)

Apple文档:

When a device receives a background notification, the system wakes your app in the background. On iOS it calls your app delegate’s application:didReceiveRemoteNotification:fetchCompletionHandler: method. On watchOS, it calls your extension delegate’s didReceiveRemoteNotification:fetchCompletionHandler: method. Your app has 30 seconds to perform any tasks and call the provided completion handler. For more information, see Handling Notifications and Notification-Related Actions.

编辑: @ archilo20您的项目是否启用了后台模式?

此设置位于目标->功能->背景模式->远程通知

确保启用它。

编辑28/08:

尝试这个答案:

Answer

关键点是:1.推送通知有效负载中的content-available:1和mutable-content:1。 2.启用后台抓取。