Firebase cloud messaging in iOS

Contributor - 18 August 2017 - 12min
Contributor - 18 August 2017 - 12min
Cloud messaging or push notification is one of those “topics” that gets left out. Primarily because we are too busy beautifying the app, or working on a new feature, or we think it isn’t a big deal. Push notifications are as big a deal as any. Whether you want to re-engage your users, or deliver personalised content, or display targeted advertisements, push notification is the way to go.
In this blog we will look at the pre-requisites and steps required to integrate Firebase Cloud Messaging (FCM) in iOS apps. For convenience, I have divided the content into the following sections:
There is a bonus section at the end with advanced content like sending data with FCM, etc.
Before we dive into account creation and pod installation, here is the list of pre-requisites:
FCM Introduction
Firebase is Google’s Backend as a service solution (a.k.a BaaS and MBaaS (Mobile BaaS)). Firebase offers a wonderful suite of products for client and backend and FCM is one of them.
Straight from the official docs: FCM is a cross-platform messaging solution that lets you reliably deliver messages at no cost. Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to 4KB to a client app. Firebase delivers 95% of push messages in under 250 milliseconds.
Firebase identifies each device for an app by a unique registration ID or token. This token is required to send individual push notifications. The registration ID is unique per device per app. Hence, do not worry if more than one of your apps is in a user’s device, the registration ID is different.
Why choose Firebase?
Setting up FCM
This is the most critical and time consuming step in sending FCM or Apple Push Notification Service (APNS), in general. Once this is done, sending an FCM message is as easy as issuing a curl command. Lets begin by creating an xcode project with a single view application. By the way, this tutorial is in swift 3 (of course). I know that swift 4 is out and I will upgrade to swift 4 sometime later.
Perform the following:
Next step is to create the certificate that firebase uses to send push notifications. Perform the following steps to generate a development p12 certificate:
Ok lets review what we have done till now. We have created an iPhone / iPad project, added firebase pods, created a new project in firebase console, added the GoogleService-info.plist file in our project, then registered our app in apple developer console and created certificate, generated a .p12 certificate, added it to firebase. Whew!!! that a lot of setup. The good news is we are done with the setup, now we can code. If you run into any issues you can refer firebase official docs.
Handling FCM in our project
Before we can send push notification, we need to ask user’s permission, I am sure you have seen a notification permission prompt in many iOS apps. Unless user allows our app to send notification we can’t. Here is how you request permission, since my app supports iOS 9 I have added conditional code. Make sure the AppDelegate adopts UNUserNotificationCenterDelegate. Also we want to get a hang of FCM registration Id, so we can send push notification to a particular device.
That’s it, we are basically done. Now we can send push notification. The extra code is just to get token information. Above code just prints the registration token, ideally it should be saved in some backend by mapping it with some sort of user id like email id or username. This token can be used to send individual push notification. Firebase also allows us to send data with push notifications, this data is bundled as dictionary of String and Any. Here is how to receive data:
Next step is to create the certificate that firebase uses to send push notifications. Perform the following steps to generate a development p12 certificate:
We are now done with the setup, and can start to code. If you run into any issues you can refer firebase official docs.
Handling FCM in our project
Before we can send push notification, we need to seek the user’s permission. I am sure you have seen a notification permission prompt in many iOS apps. Here is how you request permission: since my app supports iOS 9 I have added conditional code. Ensure the AppDelegate adopts UNUserNotificationCenterDelegate. Also we want to get a hang of FCM registration Id, so we can send push notification to a particular device.
That’s it, we are basically done. Now we can send push notifications. The extra code is just to get token information. Above code just prints the registration token, ideally it should be saved in some backend by mapping it with some sort of user id like email id or username. This token can be used to send individual push notifications. Firebase also allows us to send data with push notifications. This data is bundled as a dictionary of String and Any. Here is how to receive data:
Just override the following function in AppDelegate and it gets called whenever push notification is tapped or when app is open and push notification is received.
This is all there is to handling FCM message in an iOS app. This method gets called immediately if the app is in the foreground, but no notification is displayed in notification tray. In case the app is in the background, this function gets called when user taps on the notification and the app opens. Now lets move on to the last section and see how to send these push notifications.
Sending FCM push notifications
There are several ways to send FCM push notifications. The easiest is from Firebase console. Click on Notification on the left navigation pane in Firebase console of your project.
There is an option to enter text, select delivery date and target audience. Target audience could be all users, or a segment of users, or user subscribed to a particular topic, or to a single user or device (registration token is required in this case). This is good for maybe announcements or one time offers, or things like that. What we want is to be able to send push notifications programatically, for use cases like sending an offer to a user after she successfully purchases some item from your online store. Fortunately firebase provides a way for us to send notification via simple http post commands. Here is a sample structure of FCM message.
Sample JSON above has three main fields. registration ids field contains who to send this message to, notification field if present displays notification on device if (app is not in foreground), the data field is the data that gets delivered inside. Data field is very helpful in various use cases, like you receive a push notification that you have received an email from a friend, when you tap that, the email is opened automatically without taking you to inbox, this navigation is triggered based on data received in did receive remote notification. There is a lot more customization that can go inside the above JSON. You can refer to the official docs for more details.
How do you send an FCM push notification from curl command or simple http post? Here is how:
You can get your projects server key by going into project settings > cloud messaging > server key.
Here is what it looks like:
Let me know what you think. Got any questions shoot below in comments.
-Kaushal Dhruw (@drulabs twitter / github / stackoverflow)
"what a great read! http://ac.li-dev.cn/wiki/index.php?title=Here_are_a_few_Fresh_Thoughts_For_All_those_Seeking_To_Buy_Real_Estate_That_Everyone_Should_Know".
"Hello Sir, I have a question about push notification with hybrid iOS app. At the time of getting registration token with firebase account on hybrid iOS app then we are not getting token (iOS app downloaded from appstore). But when we are test on local iOS app with xcode 9.4.1 it's working fine.".
"great article! https://wikidot.win/wiki/Preserve_Time_And_Money_Together_with_Our_Online_Shopping_Suggestions_Beginning_Today".