Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Foundation
import Firebase
extension AppDelegate {
func setupNotifications(application: UIApplication) {
FIRApp.configure()
let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(self.tokenRefreshNotification),
name: kFIRInstanceIDTokenRefreshNotification, object: nil
)
}
func subscribeNotificationTopics(){
FIRMessaging.messaging().subscribeToTopic("/topics/News")
// register token to backend
}
func tokenRefreshNotification(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
NSLog("InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
func disconnectFromFcm(){
FIRMessaging.messaging().disconnect()
NSLog("Disconnected from FCM.")
}
func connectToFcm() {
subscribeNotificationTopics()
FIRMessaging.messaging().connectWithCompletion { (error) in
if (error != nil) {
NSLog("Unable to connect with FCM. \(error)")
} else {
NSLog("Connected to FCM.")
}
}
}
}A
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
setupNotifications(application)
return true
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
subscribeNotificationTopics()
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// consume notification
}
func applicationDidBecomeActive(application: UIApplication) {
connectToFcm()
}
func applicationDidEnterBackground(application: UIApplication) {
disconnectFromFcm()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment