繁体   English   中英

didReceiveRemoteNotification调用了两次

[英]didReceiveRemoteNotification called twice

我已经在我的应用程序中实现了推送通知。

当我的应用程序处于前台时,我的应用程序可以正常工作。

但是当应用程序在后台或被杀死时,我的didReceiveRemoteNotification调用了两次。

我已经创建了一个用于处理Push通知并从didFinishLaunchingWithOptionsdidReceiveRemoteNotification调用此方法的通用方法

这是我的实现:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  NSDictionary *pushDictionary = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
  if (pushDictionary) {
    [self customPushHandler:pushDictionary];
  }

  return YES;

}

和:

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


         [self customPushHandler:userInfo];

 }

和:

 - (void) customPushHandler:(NSDictionary *)notification {

     // Code to push ViewController

         NSLog(@"Push Notification"); //Got it two times when Clicked in notification banner

   }

当我的应用程序运行时,ViewController将被推送一次。 当我从通知横幅中打开我的应用程序时,我的屏幕将被按下两次。

我将NSLog放置在customPushHandler ,一次是在App处于前台时,一次是从Notification横幅启动时。

我的代码有什么问题?

当应用程序在后台运行时,该方法被调用两次,一次是在收到推送通知时,另一次是在点击该通知时。

您可以验证应用程序状态,如果应用程序处于后台,则可以忽略收到的通知。

解决方案: 两次调用远程通知方法

Swift 4代码:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        if (application.applicationState == .background) {
            completionHandler(.noData)
            return
        }

    // logic
    // call completionHandler with appropriate UIBackgroundFetchResult
}

检查didReceiveRemoteNotification中的这一条件,例如在应用程序处于后台时点击通知 这样,您可以避免两次被调用。

 - (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
      UIApplicationState state = [[UIApplication sharedApplication] applicationState];
      if (state == UIApplicationStateBackground || state == UIApplicationStateInactive || state == UIApplicationStateForeground || state == UIApplicationStateActive)
      {
          //Do checking here.
          [self customPushHandler:userInfo];
      }
}

检查我是否编辑了答案。

检查当前导航堆栈中的顶视图控制器,例如:

if(![self.navigationController.topViewController isKindOfClass:[MyClass class]]) {

           //code for pushing new controller

 }

每当您将backgroundFetch用于远程通知时,都为此添加一个完成处理程序。

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

    [self customPushHandler:userInfo];

    completionHandler(UIBackgroundFetchResultNewData)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM