In this article, I would like to share my experience of implementing Silent Push Notifications in an iOS app. The purpose of using Silent Push Notifications was to solve the problem of some services going to sleep when the phone is idle for a long period of time. Or for example, if you have a messenger app and you want the user to be able to access new/updated content and not have to wait for it to download.
Silent Push Notifications allowed us to activate the app once every 21 minutes (the minimum value we picked up so that Apple would not grant a temporary ban) and run the services in the background to update.
Provide the ability to update the content of your application, make API calls, and perform background tasks. They are sent without activating screen beeping or other visible notifications.
In fact, the application goes into an “active” state and is generally no different from a normal startup. Navigation will function, and screens will initialize, although they will not be visible on the screen. All actions called in the “didFinishLaunchingWithOptions” method will also be executed.
Silent push notifications wake up your application in the background, allowing time to download data from the server and perform tasks in the background.
First, you need to set up support for Silent Push Notifications in your application. Here is a brief overview of the steps you need to follow.
**1.1 Developer Portal \ Go to the Developer Portal on Apple’s website and make sure Background Modes and Background Fetch support are enabled.
**1.2 Provisioning Profile \ Ensure that the Provisioning Profile (linked to your App ID) includes support for Background Modes and Background Fetch.
**1.3 Enabling Remote Notifications \ In your project in Xcode, open the file AppDelegate.swift and add the following code to the method `application(_:didFinishLaunchingWithOptions:)`:
// Registration to receive notifications
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
**1.4 Signing & Capabilities \ Here you need to give permission to use push notifications
Scroll to the bottom. And tick the box for “Remote notifications.” Check the rest, depending on your needs.
After setting up Silent Push Notifications, you’ll need a handler that will respond to receiving such notifications and trigger a service. Here’s a sample code to add to your AppDelegate.swift
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Silent Push Notification processing
if let silentNotification = userInfo["aps"] as? [String: AnyObject],
silentNotification["content-available"] as? Int == 1 {
// Launch of a some service
SomeManager.shared.startUpdatingAnything()
}
// Ending a background operation
completionHandler(.noData)
}
Using the completion handler
You only have 30 seconds to execute the background request, and you should call the completionHandler on completion.
All the things you should tell your backend developers
3.1You must tell the backend which body to send. You can add additional fields at your discretion.
For notifications to be silent, you must specify “content-available”: 1.
{
“aps” : {
“content-available” : 1
},
“apns-priority” : 5,
“apns-push-type” : “background”,
}
You can read more about it
3.2 If you want to check your notifications without a backend like I do. You will need an application that emulates the backend to check.
I used
(You can skip this point and go straight to 3.2.1)
Update! On the day I published this article, apple introduced a new tool for push notifications 😅
3.2.1
“The new Push Notifications Console makes it easy to send test notifications to Apple devices through the Apple Push Notification service (APNs). You can access logs that provide insights into the delivery process and leverage tools to generate and validate tokens.” — Taken from Apple’s official
You will not need the p8 file for Push Notifications Console. You simply log in to your account and start testing. It’s also very convenient to use push notifications logging.
**3.3 Registration token \ A registration token is required to send remote notifications.
In order to send notifications to remote devices, your application must receive a registration token that the APNs (Apple Push Notification Service) uses to deliver notifications to a specific device.
The registration token is a unique identifier tied to the device and your app. When your app is launched, it communicates with APNs to receive a registration token, which can then be sent to your server. Your server uses this token to send notifications to the relevant device.
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken:Data) {
let pushToken = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
self.yourPushNotificationsService.pushTokenDidReceived(pushNotificationToken: pushToken)
}
Once you have a registration token for a particular user, you can send notifications to their remote device via your server, a third-party service (PushNotifications), or Firebase Cloud Messaging.
The process of receiving a token and sending notifications is shown in the diagram below.
3.4 Download the .p8 file
a. If your app already has normal push notifications, request the p8 key from the person in charge of push notifications on the backend or a senior/lead iOS developer.
b. If you are setting up push notifications for the first time, the following instructions are for you:
When you install the app, be sure to check whether it has Background App Refresh enabled
Settings > (scroll down) > Your app > Background App Refresh (enable)
In the process of implementing Silent Push Notifications, I have encountered a few problems which may be useful to you.
5.1 Apple’s restrictions Apple has a strict limit on how often Silent Push Notifications are sent.
If several Silent Push Notifications are sent in a row, they may stop reaching the user. To avoid this problem, I used a backend timer to ensure that Silent Push Notifications are only sent once every 21 minutes.
5.2 Error handling
It is important to handle possible errors when processing Silent Push Notifications. For example, if a service is already active, new Silent Push Notifications should be ignored to avoid having to run the service continuously and using resources unnecessarily.
5.3 Optimise battery usage
Running some services can consume a significant amount of battery power. To minimize this, I have set a limit on the time the service will run after each Silent Push Notification.
It is very important to note the following points:
5.4 The Silent Push does not work in “low power mode.”
5.5 The treatment of the silent-push system depends on several factors:
The use of silent Push notifications in the app has solved the problem of some services falling asleep when the phone is left for extended periods. Launching the service every 21 minutes after receiving a silent Push notification updates the data in the app, providing a better experience and usability.
Share your thoughts about the article. Your comments will help me expand on this research and provide additional material on the topic of the article. This will make it more useful.
I would like to dedicate my first technical article to my mentor. I want to express my sincere gratitude for your patience, politeness, and consistency while I was a junior developer.
Keep up the great work!
Also published here.