2016-01-21 45 views
4

我在我的应用程序中实现了推送通知。didReceiveRemoteNotification调用了两次

当我的应用程序是在前台,然后我的应用程序工作正常。

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

我已经处理推送通知,并要求从didFinishLaunchingWithOptions这种方法和didReceiveRemoteNotification

这里的常用方法是我实现:

- (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]; 

} 

AND:

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

    // Code to push ViewController 

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

    } 

当我的应用程序运行时,ViewController被推送一次。当我打开我的应用程序从通知栏,然后我的屏幕被推两次。

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

有什么问题在我的代码?

+0

参考http://stackoverflow.com/questions/22085234/didreceiveremotenotification-fetchcompletionhandler-open-from-icon-vs-push-not#comment51407901_22085855 –

回答

0

支票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]; 
     } 
} 

检查我编辑了我的答案。在像当前导航堆栈

+0

如果没有内部条件只有你有打电话。因为如果应用程序是从后台打开的,则应调用此方法。如果应用程序从didfinishlauch方法终止,那么您的处理程序应该被调用。 –

+0

你不是我的观点。我也从'didFinishLaunchingWithOptions'调用'customPushHandler'方法。如果我使用你的代码,我的'customPushHandler'将总是被调用两次,当我的应用程序处于前台时,我的'customPushHandler'永远不会被调用 – Dalvik

+0

应用程序不会一次调用这两种方法。它们具有文档所述的不同功能。相反,如果(pushDictionary)像这样检查if(pushDictionary!= nil)。或者在两种方法中记录pushDictionary。如果你获得相同的价值或零? –

0

检查顶视图控制器:

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

      //code for pushing new controller 

} 
0

当你使用backgroundFetch远程通知,添加完成处理了点。

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

    [self customPushHandler:userInfo]; 

    completionHandler(UIBackgroundFetchResultNewData) 
}