Customizing Notification Content in iOS before displaying to user

In this blog post, we piece together the steps involved in customizing notification content in iOS before displaying it to the user. Essentially, we will show how a chat application message can be customized to display a name for the sender’s number.

The need

In certain applications, for example chat apps, the server only saves the user’s numbers only. This is because the server cannot maintain the equivalent name of the mobile number as it is saved differently on each device. For example, the name Mr. Adam Smith can be saved as Adam, Adam Smith, Dad, Adam Smith 2, etc. Therefore, it is not possible for server to retain a name. Hence, it is upon the client, that is, the mobile app needs to display names and numbers appropriately, in notifications sent from server.

Developers can enable the application to find the equivalent name for a phone number that has sent you the message, by customizing the notification content in iOS using service and content extensions.

Let’s explore what extensions are and how to configure them, in the next few sections.

What is an extension?

Extensions are background applications, running independently from the app. They are around even when the app is not in the foreground. Service and Content extensions offer powerful new tools for customizing the notification information.

Service Extension

This object intercepts the push payloads from apps and helps developers to change content in the notification before it is presented.

Content extension

An object that presents a custom interface for a delivered local or remote notification. If you want to customize the UI of your notification you can use the content extension.

Note: Before getting started with notification extensions, the developer must be familiar with creating local and remote push notification.

 

Service Extension Setup

In the User Notifications framework, Apple introduced the Notification Service Extension. It’s a small program running in the background of your device that intercepts payload before notification center presents the push notification. In the Service Extension, you can modify your content with a UNMutablenotificationContent object modifying your content. That can be decrypting an encoded message or grabbing data in the userInfo to modify the content.

Setting up Service Extension

Here are steps to get started with the Service Extension:

  1. To set up the Notification Service Extension, you’ll need a new target in your application. In Xcode, go to File > New > Target.
  2. In the menu box that appears, select iOS. In the list that appears, select Notification Service Extension.

Notification Content in iOS

  1. Click Next and enter the product name. it is a good practice to suffix ServiceExtension to the app name (that gives more clarity) – for example, yourProductName ServiceExtention.

Notification Content in iOS

  1. Click Finish to complete setup.
  2. A dialog box appears seeking permission to activate the Service Extension Click Activate.

Using Service Extension

In the navigator a new group appears, which is the Service Extension. This group contains two files. Select the NotificationService.swift file.

This file consists of two functions and two properties. The core method used is the didReceive (Request: withContentHandler). This method assigns the content handler closure to one of the two properties. The other property, bestAttemptContent is a mutable copy of the push notification’s content. In this method, you change the content for the push notification, loading all that rich content you couldn’t fit in the payload, or do any change to the content you wish.

For example, Apple’s default template changes the title.   You can go ahead and customize your title by changing “bestAttemptContent.title”.

override func didReceive(_request: UNNotificationRequest, withContentHandler contentHandler:
@escaping (UNNotificationContent) -> Void)
{
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

let contactName = “Surya”
if let bestAttemptContent = bestAttemptContent {

// Modify the notification content here…
bestAttemptContent.title = \(contactName)”
contentHandler(bestAttemptContent)

}
}

 

Making changes in payload

Now that we have made adequate settings in the Service Extension, we will initiate changes in the payload. Ensure that you possess the key value pair in your payload’s aps directory.

 

“mutable-content”:1

Navigate to payload and add this key value pair. The result should look like this:

{
“aps”:{
“alert”:{
“title”:”9909912345″
},
“badge”:1,
“sound”:”default”,
“category”:”notification.category”,
“mutable-content”:1
},
“subtitle”: “How are you??”
}

You can test with this payload by using any 3rd party push testing tool. Here we are using NW pusher.
Notification Content in iOS

Configuring the Service Extension with user info

Follow the steps given below to configure the Service Extension:

  1. In Service Extension, click NotificationServiceExtension.swift file

The file has two functions – didReceive with contentHandler and serviceExtensionTimeWillExpire

  1. Place the custom information in the didReceive function. For example, you can change the notification title by editing this line:
bestAttemptContent.title = “custom Title”

 

  1. Place the custom information into the body, giving a list of the order, and add the subtitle to the subtitle property.

 

Note: You’ll need the userInfo dictionary. Let’s make referring to the dictionary easier by making it a constant in the function, casting it to the JSON dictionary type of [String:Any].

 

Here’s how it is done:

//get the dictionary
let userInfo = bestAttemptContent.userInfo as! [String:Any]

 

  1. Subtitles are user info in a payload but are a property of UNMutableNotificationContent, so they need to be transferred. Since it’s a dictionary entry, we’ll unwrap it and check for nil. If not nil, then we have a subtitle and can update the value. Let’s downcast the value to String when assigning it the subtitle content, since the dictionary has the value as Any.
//change the subtitle
if userInfo[“subtitle”] != nil{
bestAttemptContent.subtitle = userInfo[“subtitle”] as! String
}

 

For Example:

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler:
@escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as?UNMutableNotificationContent)
 
if let bestAttemptContent = bestAttemptContent {
// Modify the notification content here…
// bestAttemptContent.title = “Custom Title”

//Contact number from push payload has been received and the equivalent name of that number should be determined, and that name should be displayed as a notification title

let userInfo = bestAttemptContent.userInfo as! [String:Any]
guard let apsDict = userInfo[“aps”] as? [String:Any] else {return}
guard let alertDict = apsDict[“alert”] as? [String:Any] else {return}

if let contactNumber = alertDict[“title”] as? String {
let notificationTitle = findContactName(phoneNumber: contactNumber)
bestAttemptContent.title = \(notificationTitle)”
}

//change the subtitle
if userInfo[“subtitle”] != nil{
bestAttemptContent.subtitle = userInfo[“subtitle”] as! String
}
bestAttemptContent.subtitle = “How are you??”
contentHandler(bestAttemptContent)
}
}

 

Here findContactName(phoneNumber: contactNumber) is the custom method which retrieves the contact name from our contact list by comparing the mobile number which has been pushed from our payload

 

With this step we are ready with the Service Extension. In the next section, we need to configure info.plist

The Property List

We’ve a few more steps to complete before running the notification:

  1. Go back to Xcode. There one more file in the service extension we’ve yet to look at.
  2. Click on the info.plist and open NSExtension.
  3. Open the NSExtensionAttributes and access the UNNotificationExtensionCategory
  4. Content extensions run on categories, so whatever category this property is, that will be the category of the notification found in content.category. Change it to category.

 

This extension will run for only the notification.category notifications. If an extension has another category, it will not run. Remember to do this. If you forget this, the extension will not work for you.

Run the Notification

You are ready to run the notification. When you add extensions, Xcode often defaults to the run scheme for the extension. Check to make sure you are on your device run scheme for the app.

Results

In our payload we gave phone number and while receiving the notification we are getting the customized name.

Notification Content in iOS

 

References

  1. https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension
  2. https://developer.apple.com/documentation/usernotificationsui/unnotificationcontentextension
  3. https://www.pushwoosh.com/docs/ios-10-rich-notifications-integration
stealing your personal data

Are apps stealing your personal data? Part Three

In the last two posts, we explored how some mobile apps were malicious in nature and indulged in stealing your personal data for their gains. We also looked at a few steps that mobile app developers can undertake to bring stronger, more resilient mobile apps that don’t support dangerous activities of hackers.

In this final part, we will understand what you as an end user can do to stay vigilant and prevent mobile apps from stealing your personal data.

Note to end users – How to hackproof your smartphone

Fingerprints can be lifted. Use passcode

One of the biggest nightmares for an individual these days is losing their phone. While the hardware must have cost big bucks, what’s more vital is the loss of personal data that’s present – think emails containing sensitive information, photos, videos and more. While most of us secure our phones with fingerprints, it is not always safe as it is easy to lift prints. It is better to use strong passcodes. And if you have an evil twin, it is time to say goodbye to facial recognition as an unlocking medium as well.

Also, while smart unlock features such as unlocking phone when you reach home/office is cool, it is dangerous when your phone is in the wrong hands.

 

Activate Find My Device feature so that even if physically lost, phone can be locked or wiped

Another way to proof your data in the event you have lost your device is to track it online and lock it. You can even wipe it fully so that the hackers cannot glean anything from it. In Android, Find My Device helps to locate the device as well as lock it or wipe it. iPhone users can use Find my iPhone feature to locate their devices and even switch on Lost Mode.

stealing your personal data

Don’t reveal sensitive data while on Public WiFi

Never use Public WiFi to perform financial or business transactions as hackers can position themselves between you and the connection point and intercept sensitive personal and corporate data. Always use secure connections while performing such activities. According to a Kaspersky Lab report, one in five persons has been a target of cybercrime while abroad and a third (31 per cent) of them are senior business managers.

stealing your personal data

 

Review app permissions and EULA before installing

It is important to review what all permissions an app is requesting before completing installation. As said before some apps seek permissions for internet and location just to send targeted ads and make money. And before you know it, your phone is filled with unwanted ads.

 

While mobile apps have been a boon to smartphone users around the world, the security risks associated with them cannot be denied. It is in your own personal interest that you monitor your apps and eliminate those that you think might compromise your data’s safety. Also, lesser the number of apps and lesser the number of distractions, the more organized your phone and well-spent is your time.

apps stealing your personal data

Are apps stealing your personal data? Part Two

In the previous post, we looked at how some mobile apps can be malicious and attempt to take advantage by stealing your personal data for monetary gains. In this part, we will explore the measures that mobile app developers can take while building apps to make them more secure and prevent critical personal data loss.

Note to developers – Building secure mobile apps

Ensure libraries are free of vulnerabilities

Developers must be cautious while using third-party libraries as they could contain malicious code or could possess security flaws. Ensure that the code is tested thoroughly before being used in the app development.

Application sandboxing against malware

While building and testing apps, it is a good practice to follow sandboxing. This helps to isolate application data and code execution from other apps. A sandboxing approach helps execute untested or untrusted programs or code, possibly from unverified or untrusted third parties or websites, without risking harm to the host machine or operating system.

stealing your personal data

Don’t ask too many permissions to sensitive information

A simple app such as a flashlight does not require permission to access internet and location. These days users are concerned about data privacy issues and hence do not prefer apps that need permissions which they find unnecessary. Therefore, tuning down on number of permissions might help increase user adoption. In fact, one of the flashlight apps has put up a permission comparison screenshot to showcase less permissions as a USP:

stealing your personal data

Validate input fields to prevent SQL injection attacks

SQL injection is an attack technique that takes advantage of applications that don’t correctly validate user-supplied requests before passing them to the associated backend database. Using normal request channels such as form data, scripts and URLs, hackers can pass malicious SQL queries and commands to a database if they are not thoroughly checked first. By validating input fields and sanitizing data inputs regularly and monitoring input logs, threats like SQL injections can be thwarted.

GDPR regulations and what it means for mobile apps

From May 25 2018 onwards, GDPR will be applicable to all websites and mobile apps which serve users who are citizens of EU. Developers must ensure that they adhere to the EU guidelines and ensure greater data protection for app users. Some of the guidelines are to collect only vital information, encrypt that data and allow users to delete/modify said data at any point of time.

We have looked at some steps the developers can undertake to embed security in mobile apps right from design and development stages. In the next post we will explore how you as a user can protect yourselves from malicious mobile apps and prevent them from stealing your personal data.