paint-brush
A Comprehensive Guide to Silent Push Notifications in iOS: A Step-by-Step Walkthroughby@vladosius
219 reads

A Comprehensive Guide to Silent Push Notifications in iOS: A Step-by-Step Walkthrough

by Vladislav Mokrov7mJuly 25th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this article, I would like to share my experience of implementing Silent Push Notifications in an iOS app.
featured image - A Comprehensive Guide to Silent Push Notifications in iOS: A Step-by-Step Walkthrough
Vladislav Mokrov HackerNoon profile picture
0-item

Introduction

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.

Silent Push Notifications

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.


1. Setting up Silent Push Notifications

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.



2. Handling Silent Push Notifications

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.


3. Backend

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 here.


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 PushNotifications.


(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 Push Notifications Console


“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 website.


Taken from Apple’s official website (https://developer.apple.com/notifications/push-notifications-console/)


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.


Source: https://betterprogramming.pub


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:


  1. Go to Apple developer account and go to Certificates, Identifiers & Profiles.
  2. Go to the Keys section and click on a new key using Add button(+).
  3. Choose a unique name for the key and select the Apple Push Notification service (APN) checkbox. Click continue and then confirm.
  4. Note and save the key ID. Click Download to generate and save the key. !!! Please note you have to save the key in a secure place because you can’t download the key more than once. Do not rename Auth key file.


4. After installing the app on your physical device

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)


5. Problems and solutions

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:


  • Amount of free memory available: when you close an application, the system creates a snapshot of the memory used and assigns points to the Silent Push processing speed. If your application is training a machine learning model or using more than 400 MB of memory, the system may refuse to process the push notification. It is therefore recommended that you try to minimize resource usage and free up memory when switching to background mode.
  • Battery charge level.
  • Frequency of push notifications: the system can handle silent push notifications no more frequently than once every 20 minutes.
  • Time of day: the system can change its attitude towards handling push notifications depending on the time of day.
  • Phone charging status: if the device is charging, the system may be more prone to handle silent push.
  • App crash: if your app crashes, the system will probably not handle the silent push and may assign penalty points. So when you put your phone on charge and get your first silent push the next morning, the system will gradually increase the likelihood of handling push notifications and reduce the penalty points over time.


Conclusion

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.