EQOxx123 EQOxx123 - 5 months ago 1142
iOS Question

iOS Firebase Push Notifications : How To Give Firebase User's Device Token And Send Notification

Somewhat recently at the Google I/O event Google renovated Firebase and added a lot of new features, and touched up on the remaining ones. I have been trying to implement the iOS Push Notifications via Firebase into my app through the most basic level, so I created a very simple app that really does nothing besides receive remote push notifications. Inside of Firebase, I have uploaded my certificate and within Xcode my provisioning profiles have been added to both the target and project, and in Firebase I have uploaded the correct certificate. Below is the code contained inside of my

AppDelegate.swift
file but because my
ViewController.swift
is "empty," I did not include it. Although there are no crashes or runtime errors, when I load the app, I accept the notifications. Then, I exit the app and turn off my device. In Firebase, I send the notification to the correct app. After a couple of minutes, in Firebase it says the notification was "Completed". However, I never received the notification on the device. So, in conclusion, I need a solution to send Firebase this
deviceToken
and then use 'Firebase Notifications' to send the push notification Message. Any help for my code or in general would be greatly appreciated and I hope this helps future viewers. Thank you! My code in
AppDelegate.swift
:

import UIKit
import Firebase
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

FIRApp.configure()

let notificationTypes : UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]

let notificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)

application.registerForRemoteNotifications()
application.registerUserNotificationSettings(notificationSettings)

return true
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

print("Device Token: \(deviceToken)")

}

func applicationWillResignActive(application: UIApplication) {

}

func applicationDidEnterBackground(application: UIApplication) {

}

func applicationWillEnterForeground(application: UIApplication) {

}

func applicationDidBecomeActive(application: UIApplication) {

}

func applicationWillTerminate(application: UIApplication) {

}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

print("MessageID : \(userInfo["gcm.messgae_id"]!)") // or gcm_etc...

print(userInfo)

}


}

Answer

Docs are pretty poor for the FCM for iOS now.

Follow the sample app they have on github

Important part added here :

import Firebase
import FirebaseInstanceID
import FirebaseMessaging

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Register for remote notifications
    if #available(iOS 8.0, *) {
      let settings: UIUserNotificationSettings =
      UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
      application.registerUserNotificationSettings(settings)
      application.registerForRemoteNotifications()
    } else {
      // Fallback
      let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
      application.registerForRemoteNotificationTypes(types)
    }

    FIRApp.configure()

    // Add observer for InstanceID token refresh callback.
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotificaiton),
        name: kFIRInstanceIDTokenRefreshNotification, object: nil)

    return true
  }

 func tokenRefreshNotificaiton(notification: NSNotification) {
    let refreshedToken = FIRInstanceID.instanceID().token()!
    print("InstanceID token: \(refreshedToken)")

    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
  }
  // [END refresh_token]

  // [START connect_to_fcm]
  func connectToFcm() {
    FIRMessaging.messaging().connectWithCompletion { (error) in
      if (error != nil) {
        print("Unable to connect with FCM. \(error)")
      } else {
        print("Connected to FCM.")
      }
    }
  }

Now your token has been sent to the FCM server

Comments