Rich push notifications in Android & iOS

A rich push notification is a push notification with a rich media attachment. Mobile Foundation v8.0 supports different rich push notifications for both Android & iOS platform. In this post, we describe how to use the supported Rich Notiifications.

Android Rich Push Notifications

For Android platform, three types of notification styles are supported.

  1. PICTURE_NOTIFICATION
  2. BIGTEXT_NOTIFICATION
  3. INBOX_NOTIFICATION

Let us see in detail how to use each notification style.

PICTURE_NOTIFICATION

This style is used to display the image as part of the notification message. It shows a small icon upon receiving notification and shows the full image on expanding the notification, in the notification shade.

   

Following is a sample JSON payload to achieve this. The payload provides only the URL of the image to be displayed and image is loaded by the device. Ensure that the URL is accessible by the device.

{
   "message":{
      "alert":"Picture Notification for Android devices ",
      "url":"www.ibm.com"
   },
   "target":{
      "platforms":[
         "G"
      ]
   },
   "settings":{
      "gcm":{
         "style":{
            "notification_type":"PICTURE_NOTIFICATION",
            "url":"http://www.pocketables.com/images/2013/01/android-4.2-notification-toggles.jpg",
            "title":"Here is the latest book Released."
         }
      }
   }
}

BIGTEXT_NOTIFICATION

This style is used to show long text messages as part of notifications. By default, it shows a small summary line upon receiving notification. The notification can be expanded within the notification shade to see the complete content. This is helpful when the push payload contains long text.

Following is a sample JSON payload. We provide the long text message to be displayed with **text** and message in **alert** will be displayed as summary.

{
   "message":{
      "alert":"Take a Look in new book ",
      "url":"www.ibm.com"
   },
   "target":{
      "platforms":[
         "G"
      ]
   },
   "settings":{
      "gcm":{
         "style":{
            "notification_type":"BIGTEXT_NOTIFICATION",
            "text":"Looking back on a childhood filled with events and memories, I find it rather difficult to pick one that leaves me with the fabled warm and fuzzy feelings. As the daughter of an Air Force major, I had the pleasure of traveling across America in many moving trips. I have visited the monstrous trees of the Sequoia National Forest, stood on the edge of the Grand Canyon and have jumped on the beds at Caesar's Palace in Lake Tahoe",
            "title":"Snippet from book."
         }
      }
   }
}

INBOX_NOTIFICATION

This style is used to show messages in style of inbox. By default, it shows a small summary upon receiving notifications and complete list of messages on expanding the notifications in the notification shade.

login     userlist

Following is a sample JSON payload. We provide different messages to be displayed as a list in **lines** and message in **alert** is displayed as summary.

{
   "message":{
      "alert":"Top books for this week ",
      "url":"www.ibm.com"
   },
   "target":{
      "platforms":[
         "G"
      ]
   },
   "settings":{
      "gcm":{
         "style":{
            "notification_type":"inbox_notification",
            "lines":[
               " Normal People",
               "Everything Inside",
               "The Memory Police"
            ],
            "title":"Here is the list of new books."
         }
      }
   }
}

iOS Rich Push Notifications

For iOS Mobile Foundation supports the following additional features for messages.

  1. Title and Subtitle
  2. Localised arguments in message
  3. Image Notifications

Title and Subtitle

iOS offers feature to provide both title and subtitle strings as part of message. To provide a title to the notification, we use `title` and for description of the notification we use `subtitle`.

login

Following is a sample JSON payload.

{
   "message":{
      "alert":"Now discount is available on all books, lets hurry..."
   },
   "target":{
      "platforms":[
         "A"
      ]
   },
   "settings":{
      "apns":{
         "title":"FLASH SALE",
         "subtitle":"10% disount available on each order"
      }
   }
}  

Localized arguments in message

If the text of your notification messages is predetermined, you can store your message strings in the Localizable.strings file of your app bundle and use the title-loc-key, subtitle-loc-key, and loc-key payload keys to specify which strings you want to display. Your localized strings might contain placeholders so that you can insert content dynamically into the final string.

login

Below listing shows an example of a payload with a message that is derived from an app-provided string. The titleLocArgs key contains an array of replacement variables to substitute into the string.

{
   "message":{
      "alert":"Now discount is available on all books, lets hurry..."
   },
   "target":{
      "platforms":[
         "A"
      ]
   },
   "settings":{
      "apns":{
         "titleLocKey":"MyTitleString",
         "titleLocArgs":[
            "John"
         ],
         "locKey":"MyLocalizedString",
         "locArgs":[
            "Monday",
            "Thursday"
         ]
      }
   }
}

Image notifications

Just like Android devices, iOS also allows images as part of the notifications. For this, we need to add service extension to the app.

login   userlist

Go to your xcodeproj in Xcode > Add Target > Notification Service Extension >Next > Finish > Activate Scheme Content.

After adding serviceExntesion, modify the code in NotificationService.swift with the following snippet so that the app reads the arguments sent to display images.

//
//  NotificationService.swift
//  NotificationExtension
//

import UserNotifications

class NotificationService: UNNotificationServiceExtension {
    
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
    
    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        
        
        if let urlString = request.content.userInfo["attachment-url"] as? String, urlString != "" {
            
            if let fileUrl = URL(string: urlString ) {
                // Download the attachment
                URLSession.shared.downloadTask(with: fileUrl) { (location, response, error) in
                    if let location = location {
                        // Move temporary file to remove .tmp extension
                        let tmpDirectory = NSTemporaryDirectory()
                        let tmpFile = "file://".appending(tmpDirectory).appending(fileUrl.lastPathComponent)
                        let tmpUrl = URL(string: tmpFile)!
                        try! FileManager.default.moveItem(at: location, to: tmpUrl)
                        
                        // Add the attachment to the notification content
                        if let attachment = try? UNNotificationAttachment(identifier: "", url: tmpUrl, options:nil) {
                            
                            self.bestAttemptContent?.attachments = [attachment]
                        }
                    }
                    // Serve the notification content
                    contentHandler(self.bestAttemptContent!)
                    }.resume()
            }
            
        } else {
            contentHandler(bestAttemptContent!)
        }
        
        
    }
    
    override func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
    
}

Following is an example of a payload with images that are sent to devices. The link to the image is provided in the argument attachmentUrl.

{
   "message":{
      "alert":"Now discount is available on all books, lets hurry..."
   },
   "target":{
      "platforms":[
         "A"
      ]
   },
   "settings":{
      "apns":{
         "attachmentUrl":"https://image.freepik.com/free-vector/flash-sale-background_23-2147732906.jpg"
      }
   }
}
Inclusive terminology note: The Mobile First Platform team is making changes to support the IBM® initiative to replace racially biased and other discriminatory language in our code and content with more inclusive language. While IBM values the use of inclusive language, terms that are outside of IBM's direct influence are sometimes required for the sake of maintaining user understanding. As other industry leaders join IBM in embracing the use of inclusive language, IBM will continue to update the documentation to reflect those changes.
Last modified on July 23, 2020