Skip to content

Instantly share code, notes, and snippets.

@besilva
Created August 26, 2019 04:25
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 besilva/de0061e42f30fa212a3b2747d45bef9f to your computer and use it in GitHub Desktop.
Save besilva/de0061e42f30fa212a3b2747d45bef9f to your computer and use it in GitHub Desktop.
Firebase Cloud Messaging Manager
//
// FCMManager.swift
// FirebaseExamples
//
// Created by Bernardo Silva on 26/08/19.
// Copyright © 2019 Bernardo. All rights reserved.
//
import Foundation
import UIKit
import Firebase
class FCMManager: NSObject, UNUserNotificationCenterDelegate {
func registerForNotifications(application: UIApplication) {
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()
Messaging.messaging().delegate = self
}
func getToken() {
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instance ID: \(error)")
} else if let result = result {
print("Remote instance ID token: \(result.token)")
}
}
}
}
extension FCMManager: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment