firebase iOS not receive push notifications

18,284

Solution 1

The first thing I see is there's no call to connect to FIRMessaging. Try adding this to your AppDelegate:

func applicationDidBecomeActive(application: UIApplication) {
    FIRMessaging.messaging().connectWithCompletion { error in
        print(error)
    }
}

Solution 2

Use the following code.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    if #available(iOS 10.0, *)
    {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.currentNotificationCenter().delegate = self
        UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert])          { (granted, error) in
                if granted
                {
                //self.registerCategory()
             }
         }
         // For iOS 10 data message (sent via FCM)
         FIRMessaging.messaging().remoteMessageDelegate = self
    }
    else
    {
        let settings: UIUserNotificationSettings =  UIUserNotificationSettings(forTypes: [.Alert,.Badge,.Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }          
    application.registerForRemoteNotifications()        
    //Configuring Firebase
    FIRApp.configure()
    // Add observer for InstanceID token refresh callback.
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)     
     return true
}

//Receive Remote Notification on Background
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{
    FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Prod)
}

func tokenRefreshNotification(notification: NSNotification)
{
    if let refreshedToken = FIRInstanceID.instanceID().token()
    {
            print("InstanceID token: \(refreshedToken)")
    }
    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
}

func connectToFcm()
{
    FIRMessaging.messaging().connectWithCompletion { (error) in
            if (error != nil)
            {
                print("Unable to connect with FCM. \(error)")
            }
            else
            {
                print("Connected to FCM.")
            }
    }
}

func applicationDidBecomeActive(application: UIApplication)
{            
    connectToFcm()
}

Solution 3

You might be using Data or aps key in PUSH JSON which is used to send notifications to devices. It should work properly but in rare cases, it not works, even it'll give you success in fcm/send api but notification will not reach particular devices. This problem usually occurs in iOS devices.

A solution which worked for me is add notification key instead of Data.

{ 
    "to" : "device token",
    "notification":{
            "body": "test",
            "title": "test"
                }
}

If you are sending from Backend OR you don't have access of Firebase console. Then you can test and send notification via POSTMAN also. But you must have SERVER KEY, which can be got from Firebase console under Cloud Messaging settings.

API: https://fcm.googleapis.com/fcm/send
Method: POST
Headers:
"Content-Type"=application/json
"Authorization"="key=YOUR SERVER KEY" //You must add key= above the server key.
{ 
    "to" : "your device token",
    "notification":{
            "body": "test",
            "title": "test"
                }

}

ANOTHER DETAILED AND FULL PAYLOAD IF YOU NEED TO SEE WHAT WE CAN SEND IN FIREBASE NOTIFICATION:

{
"to":"device token",
"notification":{
"data":{
"avatar":"",
"body":"",
"key_notification":"0",
"type_notification":"1",
"deviceToken":"device token",
"badge":1,
"message":"your text"
},
"text":"your text",
"sound":"sound.caf",
"badge":21
},
"priority":"high"
}
Share:
18,284
alex willrock
Author by

alex willrock

Updated on June 06, 2022

Comments

  • alex willrock
    alex willrock about 2 years

    I include google firebase in my app - create google account, create google app, upload APNS certifications (.pem and in work in another service), and send push notifications from console, and my app not receive it. In Firebase console i see status complete but Approximate number of devices is "-"

    Of course I updated provisions profiles and APNS cert

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    
        // Register for remote notifications
        if #available(iOS 8.0, *) {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        } else {
            // Fallback
            let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
            application.registerForRemoteNotificationTypes(types)
        }
    
    
        FIRApp.configure()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotificaiton),
                                                         name: kFIRInstanceIDTokenRefreshNotification, object: nil)
    }      
    
     func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    
        print(userInfo)
    }
    
    func tokenRefreshNotificaiton(notification: NSNotification) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
    
            User.sharedUser.googleUID = refreshedToken
        }
    }
    
    
    func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], withResponseInfo responseInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
    
        print(userInfo)
    }
    
        func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Prod)
    }
    
    func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], withResponseInfo responseInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
    
        print(userInfo)
    }
    
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    
    
        print(userInfo)
    }
    
    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    
        print("ошибка")
        print(error)
        print(error.description)
    
    }
    
  • alex willrock
    alex willrock about 8 years
    thanks :) it's work perfect, i renew my cert and add this code