Skip to content

Instantly share code, notes, and snippets.

@Ilesh
Last active June 18, 2019 05:41
Show Gist options
  • Save Ilesh/dd0f96d9dc6ed9eb2711f839f3604a2c to your computer and use it in GitHub Desktop.
Save Ilesh/dd0f96d9dc6ed9eb2711f839f3604a2c to your computer and use it in GitHub Desktop.
Set up a Firebase Cloud Messaging client app on iOS
//
// IPFirebaseNotification.swift
//
//
// Created by Ilesh on 06/08/18.
// Copyright © 2018 Ilesh. All rights reserved.
//
import Foundation
import UserNotifications
//TODO:- REQUIRED INSTALL PODS IN THE PROJECTS
/**
Add below pods and post install it.
pod 'Firebase/Core'
pod 'Firebase/Messaging'
Please refere following like for the generate .plist and some steps.
https://firebase.google.com/docs/cloud-messaging/ios/client
*/
import Firebase
extension AppDelegate {
//TODO:- YOU NEED TO JUST CALL THIS METHOS IN THE `didFinishLaunchingWithOptions` METHOD.
func setUpFireBaseNotification() {
RegistrationForNotification()
FirebaseApp.configure()
Messaging.messaging().delegate = self
}
func RegistrationForNotification() -> Void {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
}
}
extension AppDelegate : UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
// APPLE DEVICE TOCKEN
NSLog("DEVICE TOKEN:- %@",deviceTokenString)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NSLog("ERROR GETING DEVICE TOKEN ")
//Singleton.shared.saveToUserDefaults(value:"ERRORGETINGDEVICETOKEN", forKey: Global.g_UserDefaultKey.DeviceToken)
}
//MARK: - 
//MARK:- NOTIFICATION RECEVED METHODS
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
notificationReceived(notification: userInfo as [NSObject : AnyObject])
switch application.applicationState {
case .inactive:
NSLog("Inactive")
break
case .background:
NSLog("Background")
break
case .active:
NSLog("Active")
break
}
IPNotificationManager.shared.GetPushProcessData(dictNoti: userInfo as NSDictionary)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if let userInfo = notification.request.content.userInfo as? [String : AnyObject] {
switch UIApplication.shared.applicationState {
case .inactive:
NSLog("willPresent Inactive")
case .background:
NSLog("willPresent Background")
case .active:
NSLog("willPresent Active")
}
IPNotificationManager.shared.GetPushProcessData(dictNoti: userInfo as NSDictionary)
}
NSLog("willPresent - Handle push from foreground" )
completionHandler(.badge)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if let userInfo = response.notification.request.content.userInfo as? [String : AnyObject] {
switch UIApplication.shared.applicationState {
case .inactive:
NSLog("didReceive Inactive")
case .background:
NSLog("didReceive Background")
case .active:
NSLog("didReceive Active")
}
IPNotificationManager.shared.GetPushProcessData(dictNoti: userInfo as NSDictionary)
}
NSLog("didReceive - Handle push from background or closed")
completionHandler()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let userInfo = userInfo as? [String : AnyObject] {
switch application.applicationState {
case .inactive:
NSLog("Inactive")
completionHandler(.newData)
case .background:
NSLog("Background")
completionHandler(.newData)
case .active:
NSLog("Active")
completionHandler(.newData)
}
IPNotificationManager.shared.GetPushProcessData(dictNoti: userInfo as NSDictionary)
}
}
func notificationReceived(notification: [NSObject:AnyObject]) {
NSLog("notificationReceived : - %@",notification)
}
}
extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
// Firebase registration token
print("Firebase registration token: \(fcmToken)")
//Singleton.shared.saveToUserDefaults(value: fcmToken, forKey: Global.g_UserDefaultKey.DeviceToken)
_ = Messaging.messaging().fcmToken
}
func application(application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
Messaging.messaging().apnsToken = deviceToken as Data
}
}
//
// IPNotificationManager.swift
//
//
// Created by Ilesh on 06/07/18.
// Copyright © 2018 Ilesh. All rights reserved.
//
import UIKit
class IPNotificationManager: NSObject {
var dicNotification : NSDictionary?
var intState :Int = 0
private override init() {
}
static let shared: IPNotificationManager = {
let instance = IPNotificationManager()
return instance
}()
//MARK: - ACTIVE STATE NOTIFICATION IN IOS 10
func GetPushProcessDataWhenActive(dictNoti:NSDictionary){
intState = UIApplication.shared.applicationState.rawValue
self.dicNotification = dictNoti
if (Global.kretriveUserData().IsLoggedIn == "1") {
DisplayNotification()
}
}
func DisplayNotification() -> Void {
if let strMSG = dicNotification?.value(forKeyPath: "aps.alert") as? String {
let alertView = UIAlertController(title: "", message:strMSG, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: { (alert) in
})
alertView.addAction(action)
let vc = Global.appDelegate.window?.rootViewController
vc?.present(alertView, animated: true, completion: nil)
}
else if let strMSG = dicNotification?.value(forKeyPath: "aps.data.message") as? String {
let alertView = UIAlertController(title: "", message:strMSG, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: { (alert) in
})
alertView.addAction(action)
let vc = Global.appDelegate.window?.rootViewController
vc?.present(alertView, animated: true, completion: nil)
}
}
//MARK: - SEND NOTIFICATION FOR INACTIVE AND BACKGROND STATE
func GetPushProcessData(dictNoti:NSDictionary){
intState = UIApplication.shared.applicationState.rawValue
self.dicNotification = dictNoti
if (Global.kretriveUserData().IsLoggedIn == "1") {
NSLog("Login --- 1" )
handlePushNotification()
}
}
//MARK: - 1ft NOTIFICATION
func handlePushNotification() -> Void {
if Global.appDelegate.navController == nil {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
NSLog("handlePushNotifBasedOnNotifType --- 2" )
self.handlePushNotifBasedOnNotifType()
}
}else{
NSLog("handlePushNotifBasedOnNotifType --- 2" )
self.handlePushNotifBasedOnNotifType()
}
}
//MARK:- 2nd NOTIFICATION
func handlePushNotifBasedOnNotifType() -> Void {
NSLog("handlePushNotifBasedOnNotifType --- 1-2")
let dictPushData = self.dicNotification
let dictAPS = dictPushData?.object(forKey: "aps") as! NSDictionary
let dictAlert = dictAPS.object(forKey: "alert") as! NSDictionary
print("Push Data :- \(String(describing: dictPushData))")
/*
Global.appDelegate.objSideMenuVC.hideSideMenu()
let arrVCs = Global.appDelegate.navController.viewControllers[0].children
var topViewController = UIViewController()
var topViewNavController = UINavigationController()
for element in arrVCs {
if element is UINavigationController {
topViewNavController = element as! UINavigationController
topViewController = (element as! UINavigationController).visibleViewController!
break
}
}
let str = dictPushData?.object(forKey: "ac") as! String
if str != "CANCEL_CUSTOMER" && str != "REJECTED" && str != "APPROVED" && str != "SUBSCRIPTION" && str != "RIDE_CANCELLED" && str != "RIDE_CANCELLED_USER"{
HDNotificationView.show(with: UIImage.init(named: "AppIcon"), title: dictAlert.object(forKey: "title-loc-key") as? String ?? "", message: dictAlert.object(forKey: "loc-key") as? String ?? "", isAutoHide: false, onTouch: { () in
// let viewController = topViewController as! JobDetailsVC
// viewController.refreshForNewRide(strRideId: dictPushData?.object(forKey: "ride_id") as! String)
HDNotificationView.hide()
})
}*/
}
}
//
// IPUserNotification.swift
//
//
// Created by Ilesh on 06/08/18.
// Copyright © 2018 Ilesh. All rights reserved.
//
import Foundation
import UserNotifications
extension AppDelegate {
func RegistrationForNotification() -> Void {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
}
}
extension AppDelegate : UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
// APPLE DEVICE TOCKEN
NSLog("DEVICE TOKEN:- %@",deviceTokenString)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NSLog("ERROR GETING DEVICE TOKEN ")
//Singleton.shared.saveToUserDefaults(value:"ERRORGETINGDEVICETOKEN", forKey: Global.g_UserDefaultKey.DeviceToken)
}
//MARK: - 
//MARK:- NOTIFICATION RECEVED METHODS
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
notificationReceived(notification: userInfo as [NSObject : AnyObject])
switch application.applicationState {
case .inactive:
NSLog("Inactive")
break
case .background:
NSLog("Background")
break
case .active:
NSLog("Active")
break
}
IPNotificationManager.shared.GetPushProcessData(dictNoti: userInfo as NSDictionary)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if let userInfo = notification.request.content.userInfo as? [String : AnyObject] {
switch UIApplication.shared.applicationState {
case .inactive:
NSLog("willPresent Inactive")
case .background:
NSLog("willPresent Background")
case .active:
NSLog("willPresent Active")
}
IPNotificationManager.shared.GetPushProcessData(dictNoti: userInfo as NSDictionary)
}
NSLog("willPresent - Handle push from foreground" )
completionHandler(.badge)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if let userInfo = response.notification.request.content.userInfo as? [String : AnyObject] {
switch UIApplication.shared.applicationState {
case .inactive:
NSLog("didReceive Inactive")
case .background:
NSLog("didReceive Background")
case .active:
NSLog("didReceive Active")
}
IPNotificationManager.shared.GetPushProcessData(dictNoti: userInfo as NSDictionary)
}
NSLog("didReceive - Handle push from background or closed")
completionHandler()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let userInfo = userInfo as? [String : AnyObject] {
switch application.applicationState {
case .inactive:
NSLog("Inactive")
completionHandler(.newData)
case .background:
NSLog("Background")
completionHandler(.newData)
case .active:
NSLog("Active")
completionHandler(.newData)
}
IPNotificationManager.shared.GetPushProcessData(dictNoti: userInfo as NSDictionary)
}
}
func notificationReceived(notification: [NSObject:AnyObject]) {
NSLog("notificationReceived : - %@",notification)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment