0

I have implemented remote notifications in my app, however I have problems with didReceiveRemoteNotification:fetchCompletionHandler:.

When the phone's screen is locked, I am getting the notification. If the user swipes the notification, app comes back to foreground and didReceiveRemoteNotification:fetchCompletionHandler: is called.

But if the app is running in the foreground, didReceiveRemoteNotification:fetchCompletionHandler: is never called. What might be the reason?

I'm working on iOS 10.3.2

mag_zbc
  • 6,801
  • 14
  • 40
  • 62

1 Answers1

1

Which iOS version you are working on ?

There are different methods for iOS 9 and iOS 10.

Below are the ones for iOS 10

    //Called when a notification is delivered to a foreground app.
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    }


    //Called to let your app know which action was selected by the user for a given notification.
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    }

For iOS 9, make sure to register your notification in didBecomeActive

UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
UIApplication.shared.registerForRemoteNotifications()

and in your didReceiveRemoteNotification

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {

if application.applicationState == .active {
//foreground state
 }

}

Best approach would be to put a debugger in didReceiveRemoteNotification and check further.

Umar Farooque
  • 2,049
  • 21
  • 32
  • Make sure to import UserNotifications check this answer https://stackoverflow.com/q/38940193/2570153 – Umar Farooque Aug 08 '17 at 11:40
  • 1
    Although I'm using Objective-C, not Swift, that is the correct answer. I forgot to implement `UNUserNotificationCenterDelegate` methods, which are called in foreground instead of `didReceiveRemoteNotification:fetchCompletionHandler:` for iOS 10 – mag_zbc Aug 08 '17 at 11:47
  • @mag_zbc Awesome ! – Umar Farooque Aug 08 '17 at 11:49