didReceiveRemoteNotification function doesn't called with FCM notification server

didreceiveremotenotification firebase
how to handle notification when app in background in firebase ios
applicationreceivedremotemessage not called
fcm background notification ios
firebase foreground notification ios
get notification data ios
firebase ios notification not received
fcm notification payload ios

I'm using FCM server for remote notifications, it worked perfectly with sending and receiving notifications.

My problem is when the device is in the background, this function func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) doesn't called.

Solutions that I've tried:

  • This function:

    userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
    

is called when user tapped on the notification. Otherwise, it's not triggered.

  • Adding "content-available": true, "priority": "high" to the payload. Also, I tried this value "content-available": 1.

  • This is my function code:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        print("userInfo: \(userInfo)")
      completionHandler(.newData);
  
    }

If you are testing with Postman then try changing "content-available": true to "content_available" : true. content-available will send notification but it doesn't call didReceiveRemoteNotification.

If you are testing with Postman then try changing "content-available": true to "​content_available" : true . content-available will send notification but it doesn't call​  The trigger is just for testing. Well, after 30 seconds, I receive the notification. To that point, everything is fine. The problem is: when it has received a reminder, it should call the didReceiveRemoteNotification()-function in the app delegate, but it doesn't. Here's my function:

All you need to see remote notification in background and foreground and show as alert when app run are this appDelegate.swift that i used in my code:

import Firebase
import UserNotifications
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate  {
    var window: UIWindow?
    let gcmMessageIDKey = "gcm_message_id"
    var deviceID : String!


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {



        // [START set_messaging_delegate]
        Messaging.messaging().delegate = self
        // [END set_messaging_delegate]

        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
        FirebaseApp.configure()
        Fabric.sharedSDK().debug = true
        return true

    }

    func showNotificationAlert(Title : String , Message : String, ButtonTitle : String ,window : UIWindow){
        let alert = UIAlertController(title: Title, message: Message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: ButtonTitle, style: .cancel, handler: nil))
        window.rootViewController?.present(alert, animated: true, completion: nil)

    }

    // [START receive_message] remote notification
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.

        print(userInfo)

    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)

    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Unable to register for remote notifications: \(error.localizedDescription)")
    }

    // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
    // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
    // the FCM registration token.
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")

        // With swizzling disabled you must set the APNs token here.
        // Messaging.messaging().apnsToken = deviceToken
    }
}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo

        // With swizzling disabled you must let Messaging know about the message, for Analytics
        // Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)



        // Change this to your preferred presentation option
        completionHandler([.alert, .badge, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }


        if let aps = userInfo["aps"] as? NSDictionary {
            if let alert = aps["alert"] as? NSDictionary {
                if let title = alert["title"] as? NSString {
                    let body = alert["body"] as? NSString
                    showNotificationAlert(Title: title as String, Message: body! as String, ButtonTitle: "Ok", window: window!)
                }
            } else if let alert = aps["alert"] as? NSString {
                print("mohsen 6 =\(alert)")
            }
        }
        // Print full message.
        print(userInfo)


        completionHandler()
    }
}
// [END ios_10_message_handling]

extension AppDelegate : MessagingDelegate {
    // [START refresh_token]
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
        deviceID = fcmToken

        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
        // TODO: If necessary send token to application server.
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }
    // [END refresh_token]
    // [START ios_10_data_message]
    // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
    // To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
    }
    // [END ios_10_data_message]


}

application(_:didReceiveRemoteNotification:fetchCompletionHandler:) However, the system does not automatically launch your app if the user has force​-quit  didReceiveRemoteNotification function doesn't called with FCM notification server 1 Push Notifications are delivered but didReceiveRemoteNotification is never called Swift

The first thing you need to check is the Background Mode > Remote Notification is on. If not, it will not be invoked in the background mode.

application(_:didReceiveRemoteNotification:) Called when your app has The app does not call this method to handle that remote notification. Instead, your  On IOS 9.xx and below, application:didReceiveRemoteNotification:userInfo fetchCompletionHandler: is called twice, once when the user receive a remote push notification and a second time if the user tap on the notification to open the app.

Step 1 – Add framework

import UserNotifications

Step 2 – Inherit AppDelegate with UNUserNotificationCenterDelegate

final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {}

Step 3 – Make appropriate changes for registerPushNotifications and call it didFinishLaunchingWithOptions

private func registerPushNotifications() {
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.currentNotificationCenter().delegate = self
        UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: { granted, error in

            if granted {
                UIApplication.sharedApplication().registerForRemoteNotifications()
            } else {
                    // Unsuccessful...
            }
          })
    } else {
        let userNotificationTypes: UIUserNotificationType = [.Alert, .Badge, .Sound]
        let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)
        UIApplication.sharedApplication().registerForRemoteNotifications()
   }
}

Step 4 – Implement new handlers

    // leave this for older versions 
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
}

// For iOS10 use these methods and  pay attention how we can get userInfo
// Foreground push notifications handler
@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
    if let userInfo = notification.request.content.userInfo as? [String : AnyObject] {
        // Getting user info
    }
    completionHandler(.Badge)
 }

// Background and closed  push notifications handler
@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)  {
    if let userInfo = response.notification.request.content.userInfo as? [String : AnyObject] {
        // Getting user info
    }
    completionHandler()
}

Send Apns message; didReceiveRemoteNotification in AppDelegate fires but it doesn't propagate into plugin function. Expected behavior add system data / custom data at step 3 & 4 without the message body / badge and it doesn’t work. didReceiveRemoteNotification doesn’t get called. Somehow one of the options in step 5 (Select and configure messaging networks) in the portal has to be filled for the notification to work.

As you tried i believe every thing , background permission is enable , content-available is the part of payload, you are also receiving notification in active state, last thing will be Power save mode, you need to check is power saving is off; as if you Phone is in power saving mode, then background refresh and other process is gone in limited state, so app will not call didReceivedNotifcation in background.

But when I use them both together, didReceiveRemoteNotification doesn't get called. Called instead of the original didReceiveRemoteNotification function as​  Although my app is on background, iOS doesn’t “wake up” my app, it doesn’t call to my method “didReceiveRemoteNotification”. I am sending my push with the tag ContentAvailable = 1 and I can see that this notification arrives at my iPhone (I activated profile PersistentConnectionLogging.mobileconfig) but "didReceiveRemoteNotification

A tap on a notification opens the app, and the content of the notification is passed to the didReceiveRemoteNotification callback in the AppDelegate . Implement  Re: Silent ios push notification ios8 doesn´t call not running app Level 1 (10 points) loretoparisi Oct 20, 2015 8:30 AM ( in response to JorgeC )

this problem a while ago, as many answers in Stack Overflow used Objective-C and the deprecated didReceiveRemoteNotification function,  The NIH examined the criteria of benefits and potential risks of gain-of-function research during the Obama and Trump administrations.

executeable code in the DidReceiveRemoteNotification function. Forms on IOS - DidReceiveRemoteNotification doesn't execute code. Setting up mobile app channel. Adobe. Campaign Classic; Getting Started; Tutorials

Comments
  • If you are testing with Postman then try changing "content-available": true to "content_available" : true. content-available will send notification but it doesn't call didReceiveRemoteNotification.
  • Yes!! it solved with this solution! Thank you, you really helped me!
  • Glad it helped. Do you mind accepting it as an answer so it can help someone else too.
  • Sure! you deserve that.
  • Yes it's checked in the project capabilities.
  • Unrelated, I don’t want you to lose hope, Firebase has loads of problems in v5, this is, and was my method in Firebase 3 , when they messed it up; I had to switch to OneSignal. They also support CURL.
  • Yes, I think so. Because I have other problems that because of Firebase versions.
  • If you ever changed your mind, it’s not much of a choice; I’ll be here for any issues with OneSignal.
  • I just tried your solution but unfortunately it doesn't called in the background.
  • "content-available": 1 should be the part of aps in payload ; Please check apple documentation (developer.apple.com/library/archive/documentation/… ).