ios - didReceiveRemoteNotification 调用了两次

标签 ios objective-c iphone push-notification xcode6

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

当我的应用程序在前台时,我的应用程序运行正常。

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

我已经制作了一个通用方法来处理推送通知并从 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 被推送一次。当我从通知横幅打开我的应用程序时,我的屏幕会被推送两次。

我在 customPushHandler 中放置了一个 NSLog,一次当应用程序处于前台时我得到了它,两次当我从通知横幅启动它时得到它。

我的代码有什么问题?

最佳答案

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

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

解决方案:Remote notification method called twice

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
}

关于ios - didReceiveRemoteNotification 调用了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920273/

相关文章:

ios - 我的游戏 View Controller UIButtons 有 IBOutlets,需要更好地组织

ios - 使用 CATransform3DMakeRotation 平滑水平翻转

objective-c - 如何使用 AFNetworking 设置超时

iphone - 在 objective-c 中枚举具有固定长度的 nsstring 的所有子字符串

objective-c - 不同的 C++ include 语句在 Objective-C header 中抛出错误

objective-c - 我将如何实现委托(delegate)将值从子 swift 类传递到父 Objective-C 类?

iphone - 如何将混合应用程序集成到 ios native 应用程序中?

iphone - 如何读取healthkit中的HKWorkoutActivityType.Running?

objective-c - Objective-C中的条件编译错误

iphone - 如何从 iphone/ipad 检索唯一标识?