Category: Apple iOS

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

iPhone X – the future of smartphones unraveled

The wait has ended. iPhone X – the future of smartphones has arrived amidst much fanfare. Unveiled at an event at the newly opened Steve Jobs Theatre (Apple Campus – Cupertino, California), the iPhone X has been subjected to both bouquets and brickbats. In this post, we explore why.

First things first, the specifications.

iPhone X comes with a host of new features, the most important ones being Facial Recognition, Augmented Reality support, Super Retina Display (Apple’s moniker for OLED display, a first for an iPhone). The home button has bid us goodbye, as the phone now responds to swipe up.

Let’s look at the specs:

Features  Details
Capacity 64 GB, 256 GB
Display 5.8” all-screen OLED, HDR
Resistance Water, Dust
Chip A11 Bionic Chip, Neural Engine
Camera 12-megapixel wide-angle and telephoto cameras, Optical zoom; digital zoom up to 10x
Video 4K video recording, Optical zoom, 6x digital zoom
Id Face ID, enabled by TrueDepth camera
Siri Improved Siri who can be activated with voice
Battery Wireless charging, lasts up to 21 hours
OS iOS 11

 

Fantastic Four Features

While the specifications are excellent as in any iPhone what is the extra special feature that makes this iPhone a fitting one to mark Apple’s tenth anniversary?

Could it be a body made entirely of smooth glass and polished stainless steel? The Facial Recognition capability that promises to adapt to changing human features? The absence of the home button? Or the impetus for Augmented Reality that is expected to be a game changer for app and gaming experience?

All are strong contenders, but perhaps it is these four that will be making waves for a while:

Facial Recognition

 

 

 

 

 

 

 

 

The Facial Recognition technology, called Face ID, captures several images of facial features with The TrueDepth camera system (a combination of light projectors and sensors), using Infrared light. Akin to the fingerprint security system that scanned our fingerprints, compared with the control set and unlocked the phone, FaceID will be comparing images to provide our gateway pass. Imagine just glancing at the phone to unlock it – simple, isn’t it?

Augmented Reality

Pokémon Go got us started on the AR rage where people were capturing monsters in red and white balls at school, near the dumpster and even at a temple entrance. Apple, too, has gained considerable advancement in AR. We saw a few applications at the event, one by Major League Baseball, where the feature lets spectators attending a live game see player statistics when they hover their phones over a particular athlete.

The technology is still at an infant stage and slowly, AR will gain momentum in smartphones.

Wireless Charging

 

 

 

 

 

 

 

 

iPhone X supports wireless charging. In fact, Apple is going full-fledged in this sphere – launching a wireless charging mat that charges all kinds of Apple devices from watch to phone to pod, all at the same time!

Animoji

Emojis are a loved feature of the internet and smartphones. Almost everyone uses them while texting, updating Facebook status and posting tweets. So why not create custom emoji? No no, we are not talking about emoji characters that look like you, but those that mirror your own expressions and movements!

Why brickbats?

Botched by Notch

 

 

 

 

 

 

 

 

 

 

The feature that has been receiving a lot of flak from a range of designers, developers and general tech aficionados is the now infamous ‘top notch’.

This section hosts a lot of cameras and sensors and is present right at the top of an otherwise all-screen phone. This might be a problem as the UI is affected while browsing sites.

While designers are expressing their consternation around the world, Apple has suggested in its Human Interface Design to:

Don’t mask or call special attention to key display features. Don’t attempt to hide the device’s rounded corners, sensor housing, or indicator for accessing the Home screen by placing black bars at the top and bottom of the screen.

FaceID is not proven

While Touch ID is a proven security measure, not many are ecstatic about using FaceID for securing their phones. It is entirely possible that identical twins might be easily able to crack the code and use your phone for hilarious or nefarious (if you have an evil twin!) reasons. Not kidding!

Final Word

The iPhone X is indeed a path breaking phone with a bevy of interesting features. It is pricey at $999, but tech aficionados will surely not give it a miss.

Watch the official film here