MoEngage Rich Notification (MORichNotification) Implementation in Swift | Swift MoEngage Push Notification | How to set up push notifications in Swift 5 iOS 2022

 How To Get Image In IOS Push Notification :

push notifications app notifications apple push notification service push service push messages ios push notification push app push api push notification service apple push notification ios notifications show notifications send notification app push notification all notifications swift push notification push notifications ios swift apple push push alert send push notification push up notification apple push service push notification server ios push push service app start push service push notification api receive notifications apple push services apple notification service service push send push apple push server push in app ios push notification service swift send notification send a notification ios send push notification push notification settings create push notification apple push notification server create push notification server push settings push message service app push notification service receive push notifications get push notifications setup push notifications ios push notification message ios notification api in app notification ios ios notification service ios push notification app message push notification set up push notifications notification ios swift push send push api ios ios send notification push message app ios push notification api push up messages apple push notification api send notification swift apple send push notification alert push notification apple push api send a push notification ios push notification server ios receive push notification ios push service swift send push notification apple push notification service api a push notification apple ios push notifications app to send push notifications app to send notifications ios push message ios notifications settings api notification push app that sends notifications push alert notifications send push message app push messages setting up push notifications ios ios push notification settings notification api ios push in notification push notification and in app notification service push notification setup push notification server push notification alert in app notification swift push notification io find push notifications in app push notifications ios the push notification push app ios notification push up push notification send ios app push push message server send push notification from server ios send notification from server app notification service ios push notification setup ios notification server ios push notification alert ios push app push notifications on create app with push notifications push notification from server ios send push notification from server push push notification ios app to receive push notifications push message api swift receive push notification ios swift notifications send ios notification ios app send push notification apple push notification setup push to app in app notification ios swift setting up push notifications apple push message push service api ios apple push notification service send notification app send push notification swift push messages setting notifications in ios swift ios notif apple notification push alert push push notification is push notification in apple ios push server


Hello Developers, Here I am giving you quick review regarding how to get image in iOS push notification (apple push notification service). 

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 :



Registering for Push notification :

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


6- Add Some Code in this to enable the NotificationViewController

//
//  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
    }

}

7- Set deployment target and Add Required frameworks






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 Notification & Set the App Group ID in Capabilities :
  • 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
Again test:- 




Post a Comment

0 Comments