Rich Push Notification in iOS
Push notification is very powerful feature to provide information without opening the app. We can add the image in push notification so that it looks more attractive than normal push notification.
Here we have taken example of fire base push notification.
1: Setup your firebase push notification in iOS app .
2: Now go file → new → targets > and select “Notification Service Extension”
3: Give some name like “NotificationService”, then it will create file alongwith its own info.plist file.
So Please open the info.plist file of “NotificationService” and allow the “Allow Arbitrary Loads” to “YES”
4: Now open NotificationService.swift file. It should look like -
import UserNotifications
class NotificationService: UNNotificationServiceExtension {
}
5: Add below Code to enable the rich push notification.
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)
guard let bestAttemptContent = bestAttemptContent else { return }
guard let attachmentUrlString = request.content.userInfo[“attachment”] as? String else { return }
guard let url = URL(string: attachmentUrlString) else { return }
URLSession.shared.downloadTask(with: url, completionHandler: { (optLocation: URL?, optResponse: URLResponse?, error: Error?) -> Void in
if error != nil {
print(“Download file error: \(String(describing: error))”)
return
}
guard let location = optLocation else { return }
guard let response = optResponse else { return }
do {
let lastPathComponent = response.url?.lastPathComponent ?? “”
var attachmentID = UUID.init().uuidString + lastPathComponent
if response.suggestedFilename != nil {
attachmentID = UUID.init().uuidString + response.suggestedFilename!
}
let tempDict = NSTemporaryDirectory()
let tempFilePath = tempDict + attachmentID
try FileManager.default.moveItem(atPath: location.path, toPath: tempFilePath)
let attachment = try UNNotificationAttachment.init(identifier: attachmentID, url: URL.init(fileURLWithPath: tempFilePath))
bestAttemptContent.attachments.append(attachment)
}
catch { print(“Download file error: \(String(describing: error))”) }
OperationQueue.main.addOperation({() -> Void in
self.contentHandler?(bestAttemptContent);
})
}).resume()
}
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)
}
}
}
6: Here “attachment” is key that will take the image and add into your push notification.
7: Now you have to change the AppDelegate.swift file. your file will look like this:
import UIKit
import FirebaseAnalytics
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
FirebaseApp.configure()
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print(“Firebase registration token: \(fcmToken)”)
if Messaging.messaging().fcmToken != nil {
Messaging.messaging().subscribe(toTopic: “/topics/news_live”)
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var tokenq = “”
for i in 0..<deviceToken.count {
tokenq = tokenq + String(format: “%02.2hhx”, arguments: [deviceToken[i]])
}
Messaging.messaging().apnsToken = deviceToken
InstanceID.instanceID().setAPNSToken(deviceToken as Data, type: InstanceIDAPNSTokenType.prod )
}
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
print(“Registered for notification!”)
Messaging.messaging().subscribe(toTopic: “/topics/news_live”)
}
@objc func tokenRefreshNotification(_ notification: Notification) {
if let refreshedToken = InstanceID.instanceID().token() {
print(“InstanceID token: \(refreshedToken)”)
let defaults = UserDefaults.standard;
defaults.set(refreshedToken, forKey: “deviceToken”);
Messaging.messaging().subscribe(toTopic: “/topics/news_live”)
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
func connectToFcm() {
// Won’t connect since there is no token
guard InstanceID.instanceID().token() != nil else {
return;
}
// Disconnect previous FCM connection if it exists.
Messaging.messaging().disconnect()
Messaging.messaging().connect { (error) in
if error != nil {
print(“Unable to connect to FCM. \(error)”)
} else {
print(“Connected to FCM.”)
}
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print(“Unable to register for remote notifications: \(error.localizedDescription)”)
}
}
// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler(UNNotificationPresentationOptions.alert)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print full message.
print(“tap on when forground app”,userInfo)
completionHandler()
}
}
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print(“Firebase registration token: \(fcmToken)”)
Messaging.messaging().subscribe(toTopic: “/topics/nutriewell_live”)
Messaging.messaging().shouldEstablishDirectChannel = true
connectToFcm()
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print(“Received data message: \(remoteMessage.appData)”)
}
// [END ios_10_data_message]
}
8: Now run your app and register with firebase.
9: Here we have taken the example to send the push notification using postman.
You can take below reference :
Here we have to make some changes for sending the rich push notification :
Please use this payload :
{
“to” : “/topics/news_live”,
“content_available” : true,
“mutable_content”: true,
“priority” : “high”,
“data”:
{
“message”: “Offer!”,
“attachment” : “http://iphoneislam.com/wp-content/uploads/2016/10/Zamen_iOS10_1-590x332.jpg",
“media_type”:”image”
},
“notification”:
{
“body”: “Enter your message”,
“sound”: “default”,
“title”:”sfshfuksgfksfgksfgksfs”
}
}
Paste this part on your post man body section .
Now your request is ready to send the image notification in app
Note: you can set the image url in “attachment” part that will show in your notification message.