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 |
import Firebase import UserNotifications class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { .... // Use Firebase library to configure APIs FirebaseApp.configure() if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().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() InstanceID.instanceID().instanceID { (result, error) in if let error = error { print("Error fetching remote instance ID: \(error)") } else if let result = result { // FCMToken.saveFCMToken(token: result.token) LoginUserModel.shared.fCMToken = result.token print("Remote instance ID token: \(result.token)") } } Messaging.messaging().delegate = self if let pushnotificationInfo = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] { if let pushnotificationInfoDictionary = pushnotificationInfo as? Dictionary<AnyHashable, Any>{ // NSLog("App has been launch through push notifications. \(pushnotificationInfoDictionary)") // UserDefaults.standard.set(pushnotificationInfoDictionary, forKey: "NotificationData") DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { self.handleRemoteNotification(notificationInfo: pushnotificationInfoDictionary, shouldInvokeUI: true) } //self.handleRemoteNotification(notificationInfo: pushnotificationInfoDictionary) } } return true } } |
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 |
//MARK:- Push Notification Handle extension AppDelegate { func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { print("DEVICE TOKEN = \(deviceToken)") Messaging.messaging().apnsToken = deviceToken } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print(error) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // Print full message. print("didReceiveRemoteNotification : \(userInfo)") completionHandler(UIBackgroundFetchResult.newData) } // The callback to handle data message received via FCM for devices running iOS 10 or above. func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) { print(remoteMessage.appData) } func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { print("Firebase registration token: \(fcmToken)") LoginUserModel.shared.fCMToken = fcmToken } } //MARK: - //@available(iOS 10, *) extension AppDelegate : UNUserNotificationCenterDelegate { //MARK:- calls when application is forground mode func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo // Print full message. print(userInfo) //Handle if app receive notification in foreground mode //self.handleRemoteNotification(notificationInfo: userInfo, shouldInvokeUI: true) // Change this to your preferred presentation option completionHandler(.sound) } //MARK:- calls when application is background mode func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo //Handle if the app receives notification in background mode and we click on notification. self.handleRemoteNotification(notificationInfo: userInfo, shouldInvokeUI: true) completionHandler() } func handleRemoteNotification(notificationInfo: Dictionary<AnyHashable, Any>, shouldInvokeUI:Bool = false) { NotificationCenter.default.post(name: NSNotification.Name.RecevedPushNotification, object: nil, userInfo: notificationInfo) clearNotifications() } func clearNotifications(){ UIApplication.shared.applicationIconBadgeNumber = 0 // UIApplication.shared.cancelAllLocalNotifications() let center = UNUserNotificationCenter.current() center.removeAllDeliveredNotifications() // To remove all delivered notifications center.removeAllPendingNotificationRequests() // To remove all pending notifications which are not delivered yet but scheduled. } } |
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 |
enum NotificationType: String { case admin = "administrator" case comment = "comment" case requestReview = "request_review" case review = "review" case requestViewProfile = "request_view_profile" case sharePost = "sharepost" case shareProfile = "shareprofile" case unIdentify = "" } class NotificationHandler { static let NOTIFICATION_TYPE_KEY = "type" static func categoryForRemoteNotification(notificationInfo:Dictionary<AnyHashable, Any>) -> NotificationType { var categoryType:String = "" if let apsData = notificationInfo["aps"] as? Dictionary<String, Any>, let notificationType = apsData[NOTIFICATION_TYPE_KEY] as? String{ categoryType = notificationType } else if let notificationType = notificationInfo[NOTIFICATION_TYPE_KEY] as? String{ categoryType = notificationType } return NotificationType(rawValue: categoryType) ?? .unIdentify } static func extract<T>(value: String, from notificationInfo: Dictionary<AnyHashable, Any>, type: T.Type) -> T? { var categoryType: T? = nil if let apsData = notificationInfo["aps"] as? Dictionary<String, Any>, let notificationType = apsData[value] as? T { categoryType = notificationType } else if let notificationType = notificationInfo[value] as? T { categoryType = notificationType } return categoryType } static func extractPayload(from notificationInfo: Dictionary<AnyHashable, Any>) -> [String: Any]? { guard let payload = NotificationHandler.extract(value: "payload", from: notificationInfo, type: String.self) else { return nil } print("User Id:: \(payload)") return JsonOperation.toDictionaryFrom(string: payload) } } |
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 |
//Make "RecevedPushNotification" key extension NSNotification.Name { static let RecevedPushNotification:NSNotification.Name = NSNotification.Name.init("RecevedPushNotification") } //Register Observer where you wants to use eg. ViewController NotificationCenter.default.addObserver(self, selector: #selector(pushNotification), name: NSNotification.Name.RecevedPushNotification, object: nil) // Do operation when you recive notification @objc func pushNotificationx(notification: Notification) -> Void { print(notification.userInfo) if let notificationInfo: Dictionary<AnyHashable, Any> = notification.userInfo { let receivedNotificationCategory = NotificationHandler.categoryForRemoteNotification(notificationInfo: notificationInfo) switch receivedNotificationCategory { case .admin: print("Notification:: Admin") if let payload: [String : Any] = NotificationHandler.extractPayload(from: notificationInfo ) { print(payload) } break } } } |