Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

didReceiveRemoteNotification called twice

I have implemented Push Notification in my App.

When my app is in the foreground then my app is working fine.

But when the app is in the background or is killed then my didReceiveRemoteNotification called two times.

I have made a common method for handling Push notification and calling this method from didFinishLaunchingWithOptions and didReceiveRemoteNotification

Here is my Implementation:

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

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

  return YES;

}

And :

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

   }

When my App is running then ViewController is pushed Once. And when I open my app From notification banner then My screen is pushed twice.

I placed a NSLog in customPushHandler and I got it one time when App is in foreground and Two time when I launch it from Notification banner.

What is issue in my code.?

like image 459
Rahul Avatar asked Jan 21 '16 09:01

Rahul


1 Answers

"When the app is in background, the method is called twice, once when you receive the push notification, and other time when you tap on that notification."

You can verify the application state and ignore the notification received if the app is in background.

Solution: Remote notification method called twice

Swift 4 code:

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
}
like image 57
Michael Lima Avatar answered Nov 15 '22 23:11

Michael Lima