Silent Remote Notifications with Swift and Firebase

With this blog post, I would like to share with you how to send Silent Push Notification using CURL or Postman HTTP client via Firebase Cloud Messaging and how to receive silent push messages in your mobile app built with Swift.

Silent push messages when received by your mobile app are not displayed to user and user of your mobile app is not aware that a new push message has arrived. When the silent message arrives, there is no sound played, no text displayed and mobile device does not vibrate. The purpose of this silent push message is to partially wake up your mobile app so that it can read from the push message the JSON payload and the data in the form of key-value pairs and then, do something with it in the background. For example, your mobile app can download some content from the server(or Firebase) and store it and have it ready for the user when they start your mobile app the next time. Is this not awesome? 🙂 

The below code examples and video tutorials demonstrate how to implement silent push notifications only, this means that your Xcode project should already have a basic configuration for regular display push notifications in place and your Firebase app should have the needed push notifications certificates or APNs Authentication Keys generated. If you need to learn how to implement regular display push notifications for your Swift mobile app with Firebase, please check videos in my video course on Firebase & Swift: Practical Examples. In my video course, I explain and demonstrate on video how to:

  • Set up your Xcode project to support push notifications,
  • Generate push notifications certificates and how to generate APNs Authentication keys,
  • How to set up your Firebase app to be able to support push notifications,
  • and more in a form of a step by step video tutorials.

but if you have all of the above mentioned set up, then let’s learn how to send and receive silent push notification in your Swift mobile app.

Silent Push Message JSON Payload

The JSON structure of a silent push message is slightly different from the regular display push notification. The main difference is that the silent push message should contain the “content_available”:true. Regular display push notifications cannot this in their JSON payload. Below is an example of a silent push notification JSON payload:

{
 "content_available":true,
 "priority":"high",
 "data": {
  "articleId":"1234"
 },
 "to":" Device Token should be provided here"
}

Also, please note: If you are sending silent remote notification via Firebase Cloud Messaging(FCM), then you should use “content_available”:true where there is an underscore(_) in the content_available key. But if you are sending silent remote notification via Apple Push Notification service, then you should use the “contentavailable” : 1 with a dash in the content-available key.

Swift Code to Accept and Read Silent Remote Notification

When mobile application receives silent remote notification, the below function will be called if provided in AppDelegate.swift file.

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
       
       print(" Entire message \(userInfo)")
       print("Article avaialble for download: \(userInfo["articleId"]!)")
       
       let state : UIApplicationState = application.applicationState
       switch state {
       case UIApplicationState.active:
           print("If needed notify user about the message")
       default:
           print("Run code to download content")
       }
       
       completionHandler(UIBackgroundFetchResult.newData)
   }

The userInfo will contain the entire push message. If you would like to read the value of articleId key, which was included in the message then you simply use userInfo[“articleId“] as it is in the code example above.

Below is a video tutorial on how to add this function in your AppDelegate.swift file.

Handle Silent Remote Notifications Video Tutorial

Send Silent Remote Notification with CURL

If you have generated needed APNs certificates or keys and have configured your Xcode project and Firebase app to support silent remote notifications, then you can use the below curl command to send a sample message to a specific device:

curl -X POST --header "Authorization: key= authorization key which you copy from Firebse app" \
   --header "Content-Type: application/json" \
   https://fcm.googleapis.com/fcm/send \
   -d "{\"to\":\" Device token comes here \",\"aps\":{\"content-available\":1}}"

 Please note that when you are sending push notification to a specific device via the Firebase Cloud Messaging(FCM) then you cannot use the APNs Device token. It should be a device token aquired the following way:

InstanceID.instanceID().token()

Below is an example of how you can acquire device token which can be used with Firebase Cloud Messaging to send a push notification to a single device. Add the below didRegisterForRemoteNotificationsWithDeviceToken function to your AppDelegate.swift file and it will be triggered when your mobile app successfully registers for remote notifications and can acquire a device token.

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    if let instanceIdToken = InstanceID.instanceID().token() {
        print("Device token which is good to use with FCM \(instanceIdToken)")
    }
}

Send Silent Push Message with CURL and Postman

Watch this video tutorial to learn how to send silent remote notification from a terminal window using CURL or Postman HTTP client.

I hope this blog post is of some value to you. If you want to learn more about how to use different Firebase services in your Swift mobile app, then I have lots of videos recorded for you in my video course Firebase & Swift: Practical Examples.

You might also want to check other great video courses available out there and I will list them below.

Happy learning!