Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ArnaudPiroelle
Created November 3, 2016 16:45
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 ArnaudPiroelle/a3f418e8ef31dc4c21235f857e93690a to your computer and use it in GitHub Desktop.
Save ArnaudPiroelle/a3f418e8ef31dc4c21235f857e93690a to your computer and use it in GitHub Desktop.
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