Skip to content

Instantly share code, notes, and snippets.

@leonmak
Last active September 27, 2020 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonmak/e3ca9211e41e82a05ffa56ca9b17e1fc to your computer and use it in GitHub Desktop.
Save leonmak/e3ca9211e41e82a05ffa56ca9b17e1fc to your computer and use it in GitHub Desktop.
Firebase Remote Notifications - IOS Swift 3

Rough notes on Remote Notifications (i.e. sent from firebase server/ console > Notifications, not Local Notifications):

  1. New single page app - Select project -> Target capabilities -> Select ON for Background modes(check remote) and push notifications

  2. pod init

   pod 'Firebase/Core'
   pod 'Firebase/Messaging'

then pod install

  1. Firebase: Create IOS project and download .plist, upload cert (next step)

  2. Similar steps to firebase walkthrough:

  • To create entry in App Id, Apple Developer account:
    • go keychain assistant -> request from CA
    • go apple.com upload CSR -> download cert & double click to install
    • go keychain select key(dev) / cert (prod) -> export and then set password to get .p12
    • go to firebase project to upload .p12 under development APN
  1. App delegate code for reference:
import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications
import FBSDKCoreKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        // Create the notificationCenter

        if #available(iOS 10.0, *) {
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().delegate = self
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { _, _ in })
        } else {
            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        
        application.registerForRemoteNotifications()
        FirebaseApp.configure()
                
        return true
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        var token = ""
        for i in 0..<deviceToken.count {
            token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
        }
        print("Registration succeeded! Token: ", token)
        let a = Messaging.messaging().fcmToken
        print("FCM token: \(a ?? "")")
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Registration failed!")
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
    }

    // Firebase notification received
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {
        
        // custom code to handle push while app is in the foreground
        print("Handle push from foreground, received: \n \(notification.request.content)")

        guard let dict = notification.request.content.userInfo["aps"] as? NSDictionary else { return }
        if let alert = dict["alert"] as? [String: String] {
            let body = alert["body"]!
            let title = alert["title"]!
            print("Title:\(title) + body:\(body)")
            self.showAlertAppDelegate(title: title, message: body, buttonTitle: "ok", window: self.window!)
        } else if let alert = dict["alert"] as? String {
            print("Text: \(alert)")
            self.showAlertAppDelegate(title: alert, message: "", buttonTitle: "ok", window: self.window!)
        }

    }
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        print("Handle tapped push from background, received: \n \(response.notification.request.content)")
        completionHandler()
    }
    
    func showAlertAppDelegate(title: String, message: String, buttonTitle: String, window: UIWindow) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: buttonTitle, style: .default, handler: nil))
        window.rootViewController?.present(alert, animated: false, completion: nil)
    }

    // Firebase ended here
}
@BushraMunawarWallet
Copy link

not working

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment