Basically, certain iOS application requires push notification functionality, and after receiving the push notification user should be able to notify using the app’s badge that few updates are posted inside the mobile application which might be useful for the user.
Increment iOS app’s badge count using 5 simple steps.
Badges are useful in applications like:
- Messaging apps
- Social apps
- E-commerce apps
- Dating apps
- Activity trackers such as to-do’s, calendars, habit trackers, etc.
This step-by-step guide helps you to set up an incremented badge for the app icon using Notification Service Extension which helps to modify the content of the original notification and then it will show the modified push notification.
Prerequisite →
- Push Notifications must be configured inside the application to increment the badge count.
- Push notification payload should contain mutable-content with a value of 1, which actually triggers NotificationServiceExtension.
NotificationServiceExtension
This service grabs the data from the push notification payload, then the user will be able to modify the content of the push notification and display the customized content onto the push notification banner including the badge count.
In our case, we are modifying the content of the push notification and incrementing the badge count when a new push notification is received.
Let’s begin to implement an incremented badge count for your app.
Step 1: Add UNNotificationServiceExtension inside the app.
1. Click on File → New → Targets → Application Extension → Notification Service Extension.
2. Add Product Name
and click on Finish
.
Step 2: Setup App Groups.
1 . Click on Project → Targets → Your app Target → Signing & Capabilities → [+] → App Groups.
2. In-App Groups, click on [+]→ Add new container → Enter group name → OK.
Make sure you’ve created a group name using the combination of ‘group’ + ‘Your app’s bundle ID’. i.e. group.com.yourApp.bundleId.
3. Make sure you’ve selected the app group which you’ve created earlier. If it is selected then it will look like the below-mentioned image.
4. Click on Project
→ Targets
→ Notification Service Extension Target
--> Signing & Capabilities
→ [+] → App Groups
.
5. Select the same App Group which you’ve created in Your app Target
.
Step 3: Setup User suit for storing badge count.
Since the user-default doesn’t work for two different targets, we need to create a user suite for passing the data between two targets.
- Open
AppDelegate.swift
and add the below code inapplicationWillEnterForeground(_ application: UIApplication)
.
Step 4: Setup Notification service extension to increment badge count.
- Open
NotificationService.swift
and replace the below code in it.