Quickstart-ios: FCMSwift. Notifications don't appear

Created on 29 May 2016  ·  99Comments  ·  Source: firebase/quickstart-ios

I send notifications like this:
{
"aps" : {
"alert" : {
"title" : "Game Request",
"body" : "Bob wants to play poker"

    },
    "badge" : 1

},

"data":{
"to_user_ids":[1],
"subject":"TEXT",
"msg":"STRINGS"
}
}

My app receives the notifications and in the "func application(application: UIApplication, didReceiveRemoteNotification userInfo.."
it prints userInfo with data. But the app doesn't show any notifications at the device and, when the app in background it neither prints message on console nor shows notifications at device.

Could you give me clear clues how to recive notifications when the app in background, handle in the code and show them on the notifications area?

Thanks

P.S.
I wasn't able to figure out it on https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH107-SW1

Most helpful comment

I think Firebase Push service is not ready for prod yet... Waste on it almost one week.

All 99 comments

Seems like your missing the notification block, the notification and data objects should be siblings within the overall message object.

@kroikie I've tried to send
{
"aps" : {
"alert" : {
"title" : "Game Request",
"body" : "Bob wants to play poker"
},
"badge" : 1
}
}

the same result

does not appear for me too while application is running

@diamo1213 @iboylmz a notification message should be formatted like this:

{
  "to" : "IID-TOKEN-OR-TOPIC",
  "notification" : {
    "body" : "great match!",
    "title" : "Portugal vs. Denmark",
    "icon" : "myicon"
  }
}

see here for more on FCM message formats. The format is the same for both iOS and Android. FCM makes the necessary platform adjustments automatically depending on the downstream client.

i've just sent from fairebase console and catch it in the code of my app. look console log:
2016-05-30 21:12:33.056: FIRMessaging receiving notification in invalid state 2
[notification: {
body = b;
e = 1;
sound = default;
sound2 = default;
title = t1;
}, m: m, collapse_key: au.com.blabla.iosapp, s: s, from: /topics/global]

strange, "invalid state 2", and look, the notification object is not in JSON format.

but in this case my device showed the message

OK. the main question is how to catch notifications object when the app is in background?

On iOS you handle foreground and background notifications in the same way, by overriding didReceiveRemoteNotification method. The only difference is when you would receive the callback to that method, that depends on whether you send a notification message or a data message and whether or not your app is in the foreground when that message is received.

The error you are seeing with "invalid state 2" seems to be an issue with analytics integration, and should not affect the receipt of the downstream message. I'll investigate further thanks for catching that.

and thanx to you Arthur for your advises.

i have print(" ##### ", userInfo) in didReceiveRemoteNotification method. but it is not works when the app in background. could you give me an example how deal with callback in this case? i've done all that kind of things in android app, but i'm new in ios.

so, my function:
func application(application: UIApplication, didReceiveRemoteNotification userInfo:[NSObject : AnyObject]
,fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{
print(" ##### ", userInfo)
}

Have a look at the the AppDelegate in the messaging quickstart in this repo. This is what your AppDelegate should look like to receive messages when your app is in the foreground and background.

Also have a look at the docs to see how to get setup on iOS.

i've deleted some methods like:
application(application: UIApplication, didRegisterUserNotificationSettings
applicationWillEnterForeground ...
and it gets notifs when in background.

Thanx @kroikie

Now I need to show notification. I think I will fire local notif/alert in some cases when get data notifs from firebase.

OK guys. I've done what I wanted from FCM notification in iOS + swift. Thanx you all.

in the following code an example how you can fire a local notif/alert when your app gets data notification from FCM. Hope it is helpful for someone ;)
`
func application(application: UIApplication, didReceiveRemoteNotification userInfo:[NSObject : AnyObject]
,fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{
print(" ##### ", userInfo)
// create a corresponding local notification
if (userInfo["subject"] != nil && userInfo["to_user_ids"] != nil){

        let notification = UILocalNotification()
        notification.alertBody = userInfo["subject"] as? String // text that will be displayed in the notification
        notification.alertAction = "open" // text that is displayed after "slide to..." on the lock screen - defaults to "slide to view"
        notification.fireDate = NSDate.init() // todo item due date (when notification will be fired). immediately here
        notification.soundName = UILocalNotificationDefaultSoundName // play default sound
        UIApplication.sharedApplication().scheduleLocalNotification(notification)
    }

}
`

@kroikie
I reinstalled the app where code the same with this repo. notification stopped to work, the app doesn't receive any data from FCM in both background and foreground. in the console i see:

2016-05-31 13:56:07.014: FIRMessaging registration is not ready with auth credentials
Unable to connect with FCM. Optional(Error Domain=com.google.fcm Code=501 "(null)")
2016-05-31 13:56:07.029: Failed to fetch APNS token Error Domain=NSCocoaErrorDomain Code=3010 "REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION" UserInfo={NSLocalizedDescription=REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION}
2016-05-31 13:56:07.030: Failed to fetch APNS token Error Domain=NSCocoaErrorDomain Code=3010 "REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION" UserInfo={NSLocalizedDescription=REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION}
Connected to FCM.
2016-05-31 13:56:10.293: Cannot subscribe to topic: /topics/global with token: (null)
2016-05-31 13:56:12.269 LabourTime[7347:] Firebase Analytics enabled
InstanceID token: fVoSO5wW3yk:APA91bEz7VIE4SWoiWJUx0Azn07dFVqz0cpeqk1cXN3hH8hcD8Y7aKzi_meWg_J9hTmlhccO19-2RTX6XCW0a6fSJLNgPrXc91FEYx7NTyPPvOXcZzp-l06UhoEsHGoZ-WKzCPJ3w
Unable to connect with FCM. Optional(Error Domain=com.google.fcm Code=2001 "(null)")

interestingly, it works again if relaunch the app. so, it seems to be some issues in Firebase/Messaging framework..

also, i sent from serverapp a notification when the app is not launched:
{"to" : "/topics/global", "notification" : {
"body" : "rrrrr"
}
}

no notification on device

I figured out that FIRInstanceID.instanceID().token()! cause crash the app from the quick-start example when the app is installed and launched first time.

It should to be:
let refreshedToken:String? = FIRInstanceID.instanceID().token()

SO, what about:

also, i sent from serverapp a notification when the app is not launched:
{"to" : "/topics/global", "notification" : {
"body" : "rrrrr"
}
}

no notification on device.
but the app subscribed on "/topics/global" and it takes and shows notifications when I send from Firebase console even when the app is launched neither in background nor in foreground.

it seems to be something wrong on FCM server that receives notifs from backends..

the requests from my appserver are OK, and gets valid response from FCM like {"message_id":7621499894723837402}

@diamo1213 try setting the FirebaseAppDelegateProxyEnabled to Boolean YES in your info.plist file.
screen shot 2016-06-02 at 10 45 27 pm

@erickva,
just sent from my server app:
{
"notification": {
"title": "test",
"body": "my message"
},
"priority": "high"
}

server app got {"message_id":9150563171907108451} in response from FCM.

but in device received nothing.

At the same time if i send from Firebase console notifications are showed on devices' natifs bar.

In background works fine with data notifs

iPhone 5. IOS last one

Will the notifications work if I kill the app from background?

Hello there im having the same problem,,,im not receiving notification from fcm in Background please help me!!

try to add this in your code
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
print("Hooray! I'm registered!")
FIRMessaging.messaging().subscribeToTopic("/topics/test")
}
and then remove content-avaliabel from your project.
But then i still want when app is closed (not running), ther the push still not working.

I had the same problem on my iphone6
In my case
when my app is in background and my server app send notifications, my didReceiveRemoteNotifications() is called. but anything did not appear in my device's screen. it is silence push notification.
How can I fix it?

sending JSON data to FCM Server (https://fcm.googleapis.com/fcm/send)
{
"to":"MY TOKEN ID",
"notification" : {
"title" : "test"
},
"content_available":true
}

and FCM Server response
{
"success": 1,
"results": [
{
"message_id": "0:1465817106189094%2d4df0482d4df048"
}
],
"failure": 0,
"canonical_ids": 0,
"multicast_id": 9136710980247659209
}

and my app's debug print:
[aps: {
alert = {
title = "test title";
};
"content-available" = 1;
}, gcm.message_id: 0:1465816999009433%2d4df0482d4df048]

I solved my problem. I changed JSON data to FCM Server.
"title":"test" -> "body":"test"

then the FCM Server work perfectly..

sending JSON data to FCM Server(https://fcm.googleapis.com/fcm/send)
{
"to":"MY TOKEN ID",
"notification" : {
"body" : "test"
}
}

so,
https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support

in iOS, notification-payload, body is not optional.

@kingleo33 i've sent from my appserver:
{
"to":"/topics/global",
"notification":{
"body":"rttrtht"
}
}
but nothing in iOS. in android app alright

@diamo1213
have you subscribed the channel in iOS app?
I have subscribed by "FIRMessaging.messaging().subscribeToTopic("/topics/news")".

In my experience,

FIRapp.configure()
FIRMessaging.messaging().subscribeToTopic("/topics/news") -> this call fail. I guess the configuration task is async.

so,
I have called "FIRMessaging.messaging().subscribeToTopic("/topics/news")" in delegate function(didRegisterUserNotificationSettings).
and work properly.

hope it helps.

@kingleo33 yes, i do FIRMessaging.messaging().subscribeToTopic("/topics/global"). i wrote here that natification works OK when the app in background or foreground. it doesn't work when the app closed/killed. but in the same time it shows notifs when i send from firebase console. so, i think that there are some problems in FCM server that receives notifs from our serverapp, not in my app. seems https://fcm.googleapis.com/fcm/send doesn't handle "notification" section of JSON from customers serverapps properly

@diamo1213

I tried sending to FCM server
{
"to":"/topics/news",
"notification":{
"body":"test..."
},
"priority": "high",
"content_available": true
}

it works.
hope it helps.

For me notifications worked both in foreground and back ground, but not when app is not running. My payload looks like this
[type: "", soundEnabled: False, gcm.message_id: 0:12345, aps: {
   alert =     {
       body = "Test Notification";
       title = MyApp;
   };
}]
and my appDelegate looks like

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("tokenRefreshNotificaiton:"), name:kFIRInstanceIDTokenRefreshNotification, object: nil)
}
func tokenRefreshNotificaiton(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token(){
print("InstanceID token: (refreshedToken)")
}
connectToFirebaseMessaging()
}
func connectToFirebaseMessaging(){
FIRMessaging.messaging().connectWithCompletion { (error) in
if error == nil {
}else{
}
print(error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print("UserInfo-> (userInfo)")
}
func applicationDidEnterBackground(application: UIApplication) {
FIRMessaging.messaging().disconnect()
}
func applicationDidBecomeActive(application: UIApplication) {
connectToFirebaseMessaging()
}

@kingleo33 i just sent from my appserver
{
"to":"/topics/global",
"notification":{
"body":"test..."
},
"priority": "high",
"content_available": true
}

the iOS app on real device was closed (not in background and foreground) at that time. and nothing in notification tray

@kingleo33 could u provide your AppDelegate code as example?

my AppDelegate.swift.

import UIKit
import Firebase
import FirebaseMessaging
import FirebaseInstanceID

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


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

        //for debug log.
        let Token = FIRInstanceID.instanceID().token()
        print("token: \(Token)")



        // Add observer for InstanceID token refresh callback.
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotificaiton),
                                                         name: kFIRInstanceIDTokenRefreshNotification, object: nil)

        return true
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
            print(userInfo)
    }


    func tokenRefreshNotificaiton(notification: NSNotification) {
        print("token refresh notifications..")
        let refreshedToken = FIRInstanceID.instanceID().token()
        print("InstanceID token refresh: \(refreshedToken)")
    }



    func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
        print("didRegisterUserNotificationSettings")
        FIRMessaging.messaging().subscribeToTopic("/topics/news")
    }

}

@kingleo33 does your app really show notifs when it is killed/closed?

@diamo1213 yes, In my case, the notifs shows when it killed.(not background).
could you provide your console message?

In my experience,
" APNS Environment in profile: development" is must exist on your console.

it is FCM server response.

{
  "message_id": 573549671617136XXXX
}

i got response {"multicast_id":5165050424619311455,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1465956637529105%c722c384c722c384"}]}

But ios device do not display notification

@kingleo33 i have the same functions. but nothing when the app closed

@diamo1213 you mentioned that while your app is not running you can still get notifications if the notification is sent from the console but not when you send using the fcm endpoint: https://fcm.googleapis.com/fcm/send

Could you try the same with the gcm endpoint:
https://gcm-http.googleapis.com/gcm/send"

and report if the same happens?

@kroikie i've just sent
{
"notification":{
"body":"test..."
},
"priority": "high",
"content_available": true
}
to https://gcm-http.googleapis.com/gcm/send.

the same happens

notifications stop to work when the app in background for long time, approx 1 hour in my case

I'm seeing a similar issue where I get a nil token upon receiving the kFIRInstanceIDTokenRefreshNotification notification. In the (documentation)[https://firebase.google.com/docs/notifications/ios/console-device#access_the_registration_token], it says:

kFIRInstanceIDTokenRefreshNotification fires when tokens are generated, so calling [[FIRInstanceID instanceID] token] in its context ensures that you are accessing a current, available registration token.

This means I should expect a valid token after that notification, right? But in my case, FIRInstanceID.instanceID().token() is sometimes nil, which seems like a bug.

I don't know if this is related, but I noticed that when successfully connecting to FCM via FIRMessaging.messaging().connectWithCompletion, the token is sometimes still nil. Also, sometimes connection to FCM fails with this undescriptive error:

Error Domain=com.google.fcm Code=2001 "(null)"

It's not clear to me why connecting to FCM sometimes fails and sometimes succeeds. Even more confusing is, why do I get a nil token even after connecting successfully and upon receiving a notification of a token change.

I think Firebase Push service is not ready for prod yet... Waste on it almost one week.

I have the same issue. Works fine sending messages via the website console, but as soon as i try to do via the API i get no visible notification. Help.

Here's some love for you gents:
http://stackoverflow.com/questions/38065813/curl-sent-firebase-cloud-messaging-alert-not-visibly-appearing-on-ios-device

It's a quick fix, simply add "priority": "high" in your payload next to "notification" etc. and the iOS Notification will work when the app is in the background.

So this will work:

json{ "to":"TOKEN ID", "notification" : { "body" : "test" }, "priority": "high" }

@DiAvisoo
thanx, but it doesn't help. I wrote here https://github.com/firebase/quickstart-ios/issues/21#issuecomment-226154085

@diamo1213 Hope you're using kFIRInstanceIDTokenRefreshNotification to get the token. I had this same issue troubling me for couple of days. I had FirebaseAppDelegateProxyEnabled set to NO in my info.plist and when I changed that to YES the push notifications started working without any issues.

@shehang I do use:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Register for remote notifications

 let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()


    FIRApp.configure()

    // Add observer for InstanceID token refresh callback.
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.tokenRefreshNotificaiton(_:)),
                                                     name: kFIRInstanceIDTokenRefreshNotification, object: nil)


    return true
}

interestingly, notifs from firebase console stopped to work too

@diamo1213 Ohh, can you check if you have FirebaseAppDelegateProxyEnabled set to YES in your plist file?

@shehang like this?
screenshot 2016-07-08 12 37 32

@diamo1213 Yeah, does it help? Not receiving pushes yet?

@shehang started to work from firebase console when the app is killed. but nothing when i send from back-end of the app:
{
"notification" : {
"title" : "test",
"body":"rttrtht"
}
}

Hi. I am successfully getting the notification but unable to get the sound. Can you please suggest what could be wrong?

@ImranNaseem1989 Send the sound in the aps tag of the push payload. Ex: (source: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html)
`{

"aps" : {

  "category" : "NEW_MESSAGE_CATEGORY"

  "alert" : {

     "body" : "Acme message received from Johnny Appleseed",

     "action-loc-key" : "VIEW"

  },

  "badge" : 3,

  "sound" : “chime.aiff"

}

}`

@ImranNaseem1989 Are you getting notification when app is killed??

@shehang your last comment with "{ "aps" : {...." is not about FCM, I think

@mrithula-quintet add "priority": "high" to the payload to get notifications while the app is killed.

@diamo1213 Actually it's the payload that I receive to the client side. You should get the "aps" tag to the client side for iOS notifications to work. If I'm not mistaken. Otherwise you wouldn't get the alerts etc.

@shehang https://firebase.google.com/docs/cloud-messaging/http-server-ref
we are talking about FCM here only.
if to use ios notifications directly then i don't need FCM

@diamo1213 Yes, so the backend is configured to send those tags to the FCM (We don't send the aps tag). But the actual notification I receive from the FCM has the "aps" tag. I just published the app I was working in to the store. No issues at all. Push works perfectly.

@shehang could you provide us code/json that you send from your back-end to https://fcm.googleapis.com/fcm/send?

thanx

It is something like this...

"data": {
//We send some values here to check from the client side
},

"notification": {

    "title": "xxxxxxx",

    "body": "xxxxxxxxxx",

    "sound": "default",

    "badge": "1"

},

@shehang i send the same but nothing when the app is killed

Sorry @diamo1213 refer to this https://firebase.google.com/docs/cloud-messaging/concept-options
I've sent you on of my old payloads. So it should follow below format

{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"priority" : "high",
"notification" : {
"body" : "This week's edition is now available.",
"title" : "NewsMagazine.com",
"icon" : "new"
},
"data" : {
"volume" : "3.21.15",
"contents" : "http://www.news-magazine.com/world-week/21659772"
}
}

@shehang in my case i send:
{
"to" : "/topics/global"
"notification" : {
"title" : "test",
"body":"rttrtht"
},
"data":{
"to_user_ids":[1],
"subject":"SUBJECT",
"msg":"MSG"
}
}

@diamo1213 When you receive a notification while the app is killed check your device logs, there should be a springboard message Jul 6 11:50:57 <device_name> SpringBoard[58] <Warning>: Low Priority Push: <app_id> - App killed

@shehang i'm new in ios development. could write where can i see device logs.

thanx

@diamo1213 In your XCode... Window -> Devices -> select the device from left pane -> Right side there should be a small arrow on the bottom which would say "Show the device console" on hover. In the console it will show you the debug prints etc. So when you receive a push it shows you that message. Means you have to increase the priority

@shehang thanx mate. very helpful

but why it doesn't show prints. i got only crashes?.. at the same time i see prints in the console log of xcode

i handle notifs in:
func application(application: UIApplication, didReceiveRemoteNotification userInfo:[NSObject : AnyObject]
,fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{....}

and it is not called when the app is killed.

@diamo1213 when the app is killed you have to handle your notification in didFinishLaunchingWithOptions
There do this,

if (launchOptions != nil){

                if let userInfo = launchOptions!["UIApplicationLaunchOptionsRemoteNotificationKey"] as? [String:AnyObject]{

//handle your notification here

}

}`

@shehang in which function must i put that code?

@diamo1213 Inside your func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
}

@diamo1213 Well, add it or make it look like it :) I mean write those method calls

Hey all,
I had the same issue. For me setting the content_available and priority fields did the trick.
Like this:

{
"to": "token",
"notification": {
"title": "Hello",
"body": "There"
},
"priority": "high",
"content_available": true
}

Good luck!

Hi, I have 3 iOS apps using Firebase Messaging, but they are receiving notifications in a different format.

In the "didReceiveRemoteNotification" method I´m printing the userInfo:

print("didReceiveRemoteNotification ", userInfo)

The result in two of my apps looks like this:

{ aps =     {
    alert =         {
        body = "body here";
        title = "title here;
    };
    badge = 3;
    "content-available" = 1;
};
"gcm.message_id" = "0:1468862214187339%9c127a139c127a13";

But in one app, the result is like this (withoud the apple "aps" payload):

didReceiveRemoteNotification {

    "collapse_key" = "my bundle";

    from = 609123480447;

    notification =     {

        body = "message here";

        e = 1;

        title = "title here";

    };

}

This happens when I send the message through my server or the Firebase Console.

So my question is:

Is there anywhere a configuration that I can choose to receive notifications in the Apple APNs format or this "notitication" format from Firebase?

If the app is killed (not in background) it just shows the notifications if it has the Apple "aps" payload.

What can I do? thank you

@livroios try to update firebase pods in the last app. i think you will get the same results as the first apps

Make sure you're calling this somewhere
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
see my stackoverflow post
http://stackoverflow.com/questions/38450595/firebase-cloud-messaging-ios-no-background-push-notification/38472349#38472349

@dnnyg33 the same result - nothing when app on killed

I was facing the same issue. Fixed it by building the response in the following way:

{
        "to" : "/topics/{userId}"
        "content_available":true,
        "priority":"high"
        "notification" : {
                "title": "",
                "body":""
        },
        "data" : {
                //custom key value pairs
        }
}

"priority":”high” makes FCM push through APNS. This allowed the app to receive the notification when the app is switched to background state.

Note: My FirebaseAppDelegateProxyEnabled is set to NO in my plist file.

BUT WHY MY APP RECEIVES AND SHOWS NOTIFICATIONS WHEN I SEND FROM FIREBASE CONSOLE??? even it is killed

Maybe I'm facing the same issue.

I am getting the Notification through Firebase correctly, but what I need is:

  • Receive the push and don't open until I touch the notification.

When the app is in background or close, this work just fine. When I touch the notification, it open the app and open what I need, but if the app is open the notification open instantly, without appear the notification or any sound.

Someone know how to give this behavior to the app...?

Sending notification messages (messages with a notification payload) is what tells FCM to use APNs, if you send a data message (message with only a data payload) this will only work when the app is in the foreground as it will be delivered through FCM.

Setting the priority field to High will generally cause your notification message to be delivered to an iOS device even when it is in the background or in some instances closed.

@TucoBZ what you are seeing is the intended behaviour, APNs does not display notifications while the app is in the foreground you have to handle the incoming message yourself in the didReceiveRemoteNotification method.

There was also an issue with retrieving APNs sandbox tokens, which has been recently been fixed, to avoid the issues related to this uninstall and reinstall the sample to be sure the generated Instance Id token from FCM is associated with an APNs token.

@diamo1213
have you resolve your problem ? because i have the same issue but now it works !

just add priority to high !

I think the original issue here has been sorted out, so I'm going to close this, feel free to create more issues if you have different or similar issues.

I have same problem, tried all this solutions and i can't make notifications work in background.
I tried with this data:

{
  "registration_ids": ["APA91bEDB9dVf-..."]
  "collapse_key": null,
  "content_available": true,
  "data": {
    "msg": "{\"model\":\"article\",\"data\":\"reload\"}"
  },
  "notification": {
    "body": "my body",
    "sound": "default",
    "title": "my title"
  },
  "priority": "high",
  "time_to_live": 3600
}
curl --header "Authorization: key=MYKEY" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d '{"registration_ids": ["APA91bEDB9dVf-..."],"collapse_key": null,"content_available": true,"notification": {"body": "my body","sound": "default","title": "my title"},"priority": "high","time_to_live": 3600,"data": {"msg":"{\"model\":\"article\",\"data\":\"reload\"}"}}'

when i open app i get all messages that were sent when app was closed.
Anyone have suggestion?
I tried with all solutions posted in answers, and still same.

I am doing the same as of @mirzadelic, and unable make it show notification in the notification tray, although broadcasts are getting received by device if app is in foreground or when it comes to foreground.

Any suggestions ?

Hi @mizadelic

I just solved this issue. Just check, have you uploaded the .p12 file on Firebase console ?
The link is below: https://firebase.google.com/docs/cloud-messaging/ios/first-message#upload_your_apns_certificate

Hi I'm using firebase to send push but not able to get "content-available" key in aps payload.

Always I got

[google.c.a.c_l: xyz, google.c.a.c_id: XXXXXXXXXXXXXXX, google.c.a.e: 1, google.c.a.ts: XXXXXXXX, gcm.n.e: 1, aps: {
alert = {
body = "XYZ";
title = XYZ;
};
badge = 0;
sound = default;
}, ]

How can i get "content-available" in payload using firebase. Is there any interface to enter this value?

same issue

@kroikie , I read your comments, according to you a data message cannot be captured when app is not open right? Also is there any way to show a data message as notification when the app is not open.

My data payload is this . I am not using notification message.
{
"to" : "/topics/test",
"priority" : "high",
"content_available": true,
"data" : {
"type":"ticket_purchase",
"title" : "Test ",
"message" : "testMessage",
"event_id":"300"
}
}

is it solved?

i got same error

Any news about that?

Now it works,Ι added the follow lines in the first View Controller app launches , and NOT in AppDelegate.swift file

import FirebaseMessaging and in viewDidLoad()

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
            FIRMessaging.messaging().subscribe(toTopic: "/topics/news")
            print("Subscribed to news topic")
        })

I also added the follow in AppDelegate for device token (Swift 3)

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        var token: String = ""
        for i in 0..<deviceToken.count {
            token += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
        }

        //Tricky line
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
        print("Device Token:", token)
    }

and in Info.plist add FirebaseAppDelegateProxyEnabled to YES

Is bundle ID of Firebase same as Xcode Bundle Identifier ?

For everyone having issues for not receiving the iOS system alert when the app is closed (running in background), I highly suggest to verify if you uploaded the correct certificates at Firebase console / Configuration / iOS as pointed by @ravi-culturealley since august.

I am getting 401 unauthorized error as my response and below is my method to send request:

private static void ApnsMethod()
{
var jGcmData = new JObject();
var jData = new JObject();

        jData.Add("message", MESSAGE);
        //jData.Add("badge", 1);
        jGcmData.Add("to", "/topics/22");
        jGcmData.Add("priority", "high");
        jGcmData.Add("data", jData);

        var url = new Uri("https://fcm.googleapis.com/fcm/send");
        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.TryAddWithoutValidation(
                    "Authorization", "key=" + FCM_API_KEY);

                Task.WaitAll(client.PostAsync(url,
                    new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                        .ContinueWith(response =>
                        {
                            Console.WriteLine(response);
                            Console.WriteLine("Message sent: check the client device notification tray.");
                            Console.ReadLine();
                        }));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Unable to send GCM message:");
            Console.Error.WriteLine(e.StackTrace);
        }
    }

and I am using Web API Key from my firebase project settings. Can anybody suggest what I have done wrong?

Was this page helpful?
0 / 5 - 0 ratings