armadiazrino

Untitled

Oct 3rd, 2022
1,245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 6.35 KB | None | 0 0
  1. //
  2. //  PushNotificationHandler.swift
  3. //  UltimateMyXL
  4. //
  5. //  Created by Armadiaz on 16/09/20.
  6. //  Copyright © 2020 Aleph. All rights reserved.
  7. //
  8.  
  9. import Firebase
  10. import UIKit
  11. import XLAlbums
  12.  
  13. class PushNotificationHandler: NSObject, MessagingDelegate, UNUserNotificationCenterDelegate {
  14.     static let shared = PushNotificationHandler()
  15.  
  16.     override init() {
  17.         super.init()
  18.     }
  19.  
  20.     // REGISTER PUSH NOTIFICATION
  21.     func registerForPushNotifications() {
  22.         if #available(iOS 10.0, *) {
  23.             // For iOS 10 display notification (sent via APNS)
  24.             UNUserNotificationCenter.current().delegate = self
  25.             let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
  26.             UNUserNotificationCenter.current().requestAuthorization(
  27.                 options: authOptions,
  28.                 completionHandler: { _, _ in })
  29.             // For iOS 10 data message (sent via FCM)
  30.             Messaging.messaging().delegate = self
  31.         } else {
  32.             let settings: UIUserNotificationSettings =
  33.                 UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
  34.             UIApplication.shared.registerUserNotificationSettings(settings)
  35.         }
  36.         UIApplication.shared.registerForRemoteNotifications()
  37.     }
  38.  
  39.     // RECEIVE TOKEN
  40.     func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
  41.         Dispatch.main {
  42.             // Send notification token to middleware
  43.             Preference.set(value: fcmToken, forKey: .kPushNotificationToken)
  44.             if CoreDataUtils.fetchAllUsers().count > 0 {
  45.                 SessionRepo().sendNotificationTokenToMW(token: fcmToken) { (response, error) in
  46.                     if let res = response {
  47.                         dprint(res)
  48.                     } else if let err = error {
  49.                         dprint(err)
  50.                     }
  51.                 }
  52.             }
  53.         }
  54.     }
  55.  
  56.     // SHOW NOTIFICATION BANNER WHEN APP IS IN FOREGROUND
  57.     func userNotificationCenter(
  58.         _ center: UNUserNotificationCenter,
  59.         willPresent notification: UNNotification,
  60.         withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  61.         let userInfo = notification.request.content.userInfo
  62.         print(userInfo)
  63.         // PRESENT NOTIFICATION BANNER
  64.         completionHandler([[.alert, .sound]])
  65.     }
  66.    
  67.     // TRIGGERED WHEN USER PRESS THE NOTIFICATION BANNER
  68.     func userNotificationCenter(
  69.         _ center: UNUserNotificationCenter,
  70.         didReceive response: UNNotificationResponse,
  71.         withCompletionHandler completionHandler: @escaping () -> Void) {
  72.         // return if there's no user
  73.         Dispatch.main {
  74.             guard CoreDataUtils.fetchAllUsers().count > 0 else {
  75.                 completionHandler()
  76.                 return
  77.             }
  78.            
  79.             // Get notification "data" payload sent from FCM
  80.             var userInfo = response.notification.request.content.userInfo
  81.            
  82.             if let moengageInfo = userInfo["app_extra"] as? [AnyHashable: Any], let screenInfo = moengageInfo["screenData"] as? [AnyHashable: Any] {
  83.                 userInfo = screenInfo
  84.             }
  85.            
  86.             var notificationPayload: NotificationPayloadModel
  87.             // Converting notification payload data (Dictionary) as NotificationPayloadModel (Struct)
  88.             if let formId = userInfo["surveyId"] as? String, !formId.isEmpty {
  89.                 notificationPayload = NotificationPayloadModel(actionType: "SURVEY", actionParam: formId)
  90.             } else {
  91.                 notificationPayload = NotificationPayloadModel(dictionary: userInfo)
  92.             }
  93.            
  94.             // check for correct user if it exist based on user subs ID
  95.             if let notificationSubID = notificationPayload.subscriptionId, !notificationSubID.isEmpty, let targetUserBySubsID = CoreDataUtils.fetchUser(with: notificationSubID) {
  96.                 // Try to switch user based on User SubscriberID
  97.                 if targetUserBySubsID.subscriberID != CoreDataUtils.getActiveUser()?.subscriberID {
  98.                     CoreDataUtils.setUserAsActive(user: targetUserBySubsID)
  99.                     Preference.set(value: targetUserBySubsID.isCorporate, forKey: .kIsEnterprise)
  100.                 }
  101.                 // check for correct user if it exist based on user MSISDN
  102.             } else if let notificationMSISDN = notificationPayload.msisdn, !notificationMSISDN.isEmpty, let targetUserByMSISDN = CoreDataUtils.fetchUserWithMSISDN(msisdn: notificationPayload.msisdn ?? "") {
  103.                 // Try to switch user based on User MSISDN
  104.                 if targetUserByMSISDN.profile?.msisdn != CoreDataUtils.getActiveUser()?.profile?.msisdn {
  105.                     CoreDataUtils.setUserAsActive(user: targetUserByMSISDN)
  106.                     Preference.set(value: targetUserByMSISDN.isCorporate, forKey: .kIsEnterprise)
  107.                 }
  108.             }
  109.            
  110.             self._processDeeplink(notificationPayload: notificationPayload)
  111.             completionHandler()
  112.         }
  113.     }
  114.  
  115.     func _processDeeplink(notificationPayload: NotificationPayloadModel) {
  116.         let dynamicLinkData = DynamicLinkModel(param: [notificationPayload.actionType ?? "": notificationPayload.actionParam ?? ""])
  117.         Preference.setStruct(dynamicLinkData, forKey: .kDynamicLinkData)
  118.         self._processPushNotification()
  119.     }
  120.  
  121.     private func _processPushNotification() {
  122.         if let tabBarController = UIApplication.shared.windows.first?.rootViewController as? XLTabBarController {
  123.             // Handle the notification when the app is in foreground but not on Dashboard
  124.             if tabBarController.selectedIndex != 0 {
  125.                 AppDelegate.shared.setTabbarAsRoot(transition: .init(direction: .fade))
  126.             } else if let navController = tabBarController.viewControllers?.first as? XLNavigationController {
  127.                 if let viewController = navController.viewControllers.first as? DashboardViewController {
  128.                     viewController.presenter.handleDynamicLink()
  129.                 } else if let viewController = navController.viewControllers.first as? DashboardHomePostpaidViewController {
  130.                     viewController.presenter.handleDynamicLink()
  131.                 }
  132.             }
  133.         }
  134.     }
  135. }
  136.  
Advertisement
Add Comment
Please, Sign In to add comment