2016-01-21 51 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) 
}