How To Get Image In IOS Push Notification :
Swift 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 which you can make more attractive push notification in iPhone app and provide the more information.
This procedure called rich notification in iOS. Here i have taken example of MoEngage push notification iOS swift .
How to implement Rich Notifications?.
Setup push notifications iOS-
SDK Integration :
Integration through CocoaPods
Cocoapods is a dependency manager for Objective C & Swift projects and makes integration easier.
1- If you don't have CocoaPods installed, you can do it by executing the following line in your terminal.
sudo gem install cocoapods
2- If you don't have a Podfile, then create one by using
pod init
command. Post this add MoEngage-iOS-SDK
pod to your pod file as shown below.pod 'MoEngage-iOS-SDK'
3- Integrate MoEngage iOS SDK by executing the following in the terminal at your project's root directory.
pod repo update pod install
4- Now, open your project workspace and check if MoEngage SDK is properly added.
MoEngage dashboard register APP_ID :
We will use this App id in AppDelegate class.
Upload apple push certificate pem file to MoEngage dashboard :
Make sure that class, where UserNotificationCenter delegate methods are implemented, should agree to
UNUserNotificationCenterDelegate
, also set the UNUserNotificationCenterDelegate
after the app launch in application:DidFinishLaunchingWithOptions:
as shown below: (In this case AppDelegate is set to be UserNotificationCenter delegate) :// // AppDelegate.swift // MoengageTest // // Created by appcodezip // import UIKit import MoEngage import UserNotifications @main class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MOMessagingDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let appGroupID = "group.test.moengage" let appID = "UR9AMSU3JAP792EK7ZEFLDEL" let appID = "APP_ID" var sdkConfig = MOSDKConfig.init(appID: appID) sdkConfig.appGroupID = appGroupID // Separate initialization methods for Dev and Prod initializations #if DEBUG MoEngage.sharedInstance().initializeTest(with: sdkConfig, andLaunchOptions: launchOptions) #else MoEngage.sharedInstance().initializeLive(with: sdkConfig, andLaunchOptions: launchOptions) #endif MoEngage.sharedInstance().registerForRemoteNotification(withCategories: nil, withUserNotificationCenterDelegate: self) MOMessaging.sharedInstance().messagingDelegate = self MoEngage.sharedInstance().appStatus(INSTALL) MoEngage.enableSDKLogs(true) if #available(iOS 10.0, *) { UNUserNotificationCenter.current().delegate = self } return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } //Remote notification get token methods========= func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { //Call only if MoEngageAppDelegateProxyEnabled is NO MoEngage.sharedInstance().setPushToken(deviceToken) print(deviceToken) let tokenParts = deviceToken.map { data -> String in return String(format: "%02.2hhx", data) } let token = tokenParts.joined() print("token-----",token) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { //Call only if MoEngageAppDelegateProxyEnabled is NO MoEngage.sharedInstance().didFailToRegisterForPush() print("Failed to register: \(error.localizedDescription)") } // Notification Clicked Callback func notificationClicked(withScreenName screenName: String?, andKVPairs kvPairs: [AnyHashable : Any]?) { if let screenName = screenName { print("Navigate to Screen:\(screenName)") } if let actionKVPairs = kvPairs { print("Selected Action KVPair:\(actionKVPairs)") } } // Notification Clicked Callback with Push Payload func notificationClicked(withScreenName screenName: String?, kvPairs: [AnyHashable : Any]?, andPushPayload userInfo: [AnyHashable : Any]) { if let screenName = screenName { print("Navigate to Screen:\(screenName)") } if let actionKVPairs = kvPairs { print("Selected Action KVPair:\(actionKVPairs)") } } // User tap on foreground Notification------------------- @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { //Call only if MoEngageAppDelegateProxyEnabled is NO MoEngage.sharedInstance().userNotificationCenter(center, didReceive: response) let userInfo = response.notification.request.content.userInfo print("tap on on forground app",userInfo) completionHandler(); } // // Handle Notifications While Your App Runs in the Foreground------------- @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert , .sound]) } }
Create new target in Xcode for notification :
1- Now go file – > new – > targets > and select “Notification Service Extension”
2- it will look like this:
import UserNotifications class NotificationService: UNNotificationServiceExtension { }
3- Add Some Code in this to enable the rich push notification.
// // NotificationService.swift // NotificationServices // // Created by appcodezip. // import UserNotifications import MORichNotification class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { MORichNotification.setAppGroupID("group.test.moengage") self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) MORichNotification.handle(request, withContentHandler: contentHandler) } override func serviceExtensionTimeWillExpire() { if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } }
4- Now go file – > new – > targets > and select Notification Content Extension
5- PushTemplateExtension Info.plist changes// // NotificationViewController.swift // PushTemplateExtension // // Created by appcodezip. // import UIKit import UserNotifications import UserNotificationsUI import MORichNotification class NotificationViewController: UIViewController, UNNotificationContentExtension { @IBOutlet var label: UILabel? override func viewDidLoad() { super.viewDidLoad() MORichNotification.setAppGroupID("group.test.moengage") } func didReceive(_ notification: UNNotification) { MOPushTemplateHandler.sharedInstance().addPushTemplate(to: self, with: notification) self.label?.text = notification.request.content.body } }
Integrate MORichNotification framework to Extension :
For integrating through CocoaPod, include MORichNotification pod for your Notification Service Extension & PushTemplateExtension as shown below, and run pod update / install command.
target 'PushTemplateExtension' do pod 'MORichNotification' use_frameworks! end target 'NotificationServices' do pod 'MORichNotification' use_frameworks! end
- Enable Push Notifications capabilities in Xcode, by selecting the build target and then Capabilities tab
- Add separate provision profile in every target MoEngage Inside handles image audio and video. No need to add code to download.
MoEngage Notification Payload :
{ "aps": { "alert": { "title": "Notification Title", "subtitle": "Notification Subtitle", "body": "Notification Body" }, "badge": 1, "sound": "default", "category": "INVITE_CATEGORY", "content-available": 1, "mutable-content": 1 }, "app_extra": { "moe_deeplink": "moeapp://screen/settings", "screenName": "Screen Name", "screenData": { "key1": "val1", "key2": "val2" } }, "moengage": { "silentPush": 1, "cid": "55f2ba15a4ab4104a287bf88", "app_id": "DAO6UGZ73D9RTK8B5W96TPYN_DEBUG", "moe_campaign_id": "55f2ba15a4ab4104a287bf88", "moe_campaign_name": "Campaign Name", "inbox_expiry": "1571905058", "webUrl": "https://google.com", "couponCode": "APP200", "media-attachment": "https://image.moengage.com/testImg.png", "media-type": "image" } }
Sent notification to MoEngage dashboard :
Now apple push notification server as MoEngage dashboard is ready to ios send push notification in iPhone iOS app
Finally- receive push notifications
---------------------------
Thanks for reading!!
Related Posts:
- An Introduction to Swift Property Wrappers
- How to remove duplicate elements from an array with Swift 5
- How to store Model Class data in User Defaults in Swift?
- Adding a Custom Font to Your IOS App
- How to big numbers YAxis format values convert to Indian Numbering Format like k(thousand), L(lakh), Cr(crore), Ar(Arab) and etc.on iOS barchart Swift
0 Comments