Skip to content

Instantly share code, notes, and snippets.

Created September 21, 2017 09:15
Show Gist options
  • Save anonymous/5082cc5878c4857a02ca6300251f690d to your computer and use it in GitHub Desktop.
Save anonymous/5082cc5878c4857a02ca6300251f690d to your computer and use it in GitHub Desktop.
import UIKit
import Firebase
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let notificationIdentifier: String = "NotificationIdentifier"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
configureFirebase(application: application)
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
Messaging.messaging().shouldEstablishDirectChannel = false
print("FCM in Background.")
}
func applicationWillEnterForeground(_ application: UIApplication) {
print("FCM in Forground.")
}
func applicationDidBecomeActive(_ application: UIApplication) {
connectToFcm()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
extension AppDelegate: UNUserNotificationCenterDelegate, MessagingDelegate {
// Registering for Firebase notifications
func configureFirebase(application: UIApplication) {
FirebaseApp.configure()
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification),
name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
//Notification.Name.MessagingRegistrationTokenRefreshed
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
// [START register_for_notifications]
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()
//print("-----firebase token: \(String(describing: Messaging.messaging().fcmToken)) ----")
}
//MARK: FCM Token Refreshed
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
// FCM token updated, update it on Backend Server
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("remoteMessage: \(remoteMessage)")
}
//Called when a notification is delivered to a foreground app.
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
//Called to let your app know which action was selected by the user for a given notification.
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("User Info = \(response.notification.request.content.userInfo)")
completionHandler()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// // If you are receiving a notification message while your app is in the background,
// // this callback will not be fired till the user taps on the notification launching the application.
// // TODO: Handle data of notification
// // Print message ID.
// if let messageID = userInfo[gcmMessageIDKey] {
// print("Message ID: \(messageID)")
// }
//
// // Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// // If you are receiving a notification message while your app is in the background,
// // this callback will not be fired till the user taps on the notification launching the application.
// // TODO: Handle data of notification
// // Print message ID.
// if let messageID = userInfo[gcmMessageIDKey] {
// print("Message ID: \(messageID)")
// }
//
// // Print full message.
print(userInfo)
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func tokenRefreshNotification(_ notification: Notification) {
if let refreshedToken = InstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
InstanceID.instanceID().setAPNSToken(deviceToken, type: InstanceIDAPNSTokenType.sandbox)
// Helpers is my NSUserDefaults Class. You must manage this token as its own.
if Helpers.getStringValueForKey(Constants.DEVICE_TOKEN).characters.count == 0 {
Helpers.setStringValueWithKey(Commons.getDeviceID(), key: Constants.DEVICE_TOKEN)
}
if Helpers.getStringValueForKey("gcm_id").characters.count == 0 {
Helpers.setStringValueWithKey("yes", key: "first_run")
if let refreshedToken = InstanceID.instanceID().token() {
let gcm_id = refreshedToken as String
Helpers.setStringValueWithKey(gcm_id, key: "gcm_id")
}
}
else{
Helpers.setStringValueWithKey("no", key: "first_run")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment