Rich Push Notification
Push notification is very use full to provide information regarding your app , some messages you can read without opening the app so that iOS 10 provide the image feature also so now you can add the image in push notification so you can make more attractive push notification in app and provide the more information.
Here i 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 will create file and also it create its own info.plist file.
So Please open the info.plist file of “NotificationService” and allow the “Allow Arbitrary Loads” to “YES”
4: it will look like this:
1 2 3 4 5 |
import UserNotifications class NotificationService: UNNotificationServiceExtension { } |
5: Add Some Code in this to enable the rich push notification.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
// // NotificationService.swift // Notification // // Created by kunal on 27/04/18. // Copyright © 2018 kunal. All rights reserved. // 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 its time to set the AppDelegate.swift file . your file will look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
// /** * Webkul Software. * @package NewsPaper * @Category Webkul * @author Webkul <support@webkul.com> * FileName: AppDelegate.swift * @Copyright (c) 2010-2019 Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html ASL Licence * @link https://store.webkul.com/license.html */ import UIKit import IQKeyboardManagerSwift import FirebaseAnalytics import FirebaseMessaging import FirebaseInstanceID import UserNotifications import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UIView.appearance().semanticContentAttribute = .forceRightToLeft UITextField.appearance().semanticContentAttribute = .forceRightToLeft UISwitch.appearance().semanticContentAttribute = .forceRightToLeft sharedPrefrence.set("ar", forKey: "language") sharedPrefrence.synchronize() UINavigationBar.appearance().tintColor = UIColor.init(named: "Navigation_TintColor") UINavigationBar.appearance().barTintColor = UIColor.init(named: "White_Color") let backImage = UIImage(named: "forward_white") UINavigationBar.appearance().backIndicatorImage = backImage UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear], for: .normal) UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: -1000.0, vertical: 0.0), for: .default) IQKeyboardManager.shared.enable = true // Configure Push Notification self.setupPushNotification(application: application, launchOptions: launchOptions) if let remoteNotif = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [String: Any] { UserDefaults.standard.set(remoteNotif, forKey: "NotificationData") UserDefaults.standard.synchronize() } return true } } extension AppDelegate { func setupPushNotification(application: UIApplication, launchOptions: [UIApplication.LaunchOptionsKey: Any]?){ //Push NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: Notification.Name.MessagingRegistrationTokenRefreshed, object: nil) 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) } if UserDefaults.standard.object(forKey: "Notification") == nil{ application.registerForRemoteNotifications() UserDefaults.standard.set(true, forKey: "Notification") UserDefaults.standard.synchronize() } } 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 as Data if Messaging.messaging().fcmToken != nil{ Messaging.messaging().subscribe(toTopic: "/topics/all") } } func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) { Messaging.messaging().subscribe(toTopic: "/topics/all") connectToFcm() } @objc func tokenRefreshNotification(_ notification: Notification) { InstanceID.instanceID().instanceID { (result, error) in if let error = error { debugPrint("Error fetching remote instange ID: \(error)") } else if let result = result { debugPrint("Remote instance ID token: \(result.token)") } Messaging.messaging().subscribe(toTopic: "/topics/all") } connectToFcm() } func connectToFcm() { // Disconnect previous FCM connection if it exists. Messaging.messaging().shouldEstablishDirectChannel = true } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) { debugPrint(userInfo) guard let notificationType = userInfo["type"] as? String else { return } if UIApplication.shared.applicationState == .inactive {// tap if notificationType == "category"{ NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pushNotificationforCategory"), object: nil, userInfo: userInfo) }else if notificationType == "post"{ NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pushNotificationforPost"), object: nil, userInfo: userInfo) }else if notificationType == "custom"{ NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pushNotificationforCustom"), object: nil, userInfo: userInfo) } } } } @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) { completionHandler(UNNotificationPresentationOptions.alert) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } // topController should now be your topmost view controller if let tabVC = topController as? UITabBarController { tabVC.selectedIndex = 0 if let navigation:UINavigationController = (topController as? UITabBarController)?.viewControllers?[0] as? UINavigationController{ navigation.popToRootViewController(animated: true) } } } guard let notificationType = userInfo["type"] as? String else { return } if notificationType == "category"{ NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pushNotificationforCategory"), object: nil, userInfo: userInfo) }else if notificationType == "post"{ NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pushNotificationforPost"), object: nil, userInfo: userInfo) }else if notificationType == "custom"{ NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pushNotificationforCustom"), object: nil, userInfo: userInfo) } completionHandler() } } extension AppDelegate : MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { Messaging.messaging().shouldEstablishDirectChannel = true connectToFcm() } func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) { debugPrint("Received data message: \(remoteMessage.appData)") } } |
8: Now run your app , and registered with firebase .
9: Here we have taken the example to send the push notification using post man.
You can take the detail reference :
Here we have to make some changes for sending the rich push notification :
Please use this parameter :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
{ "to" : "/topics/nutriewell_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.