Initialize FCM in Swift

suggest change

These steps use the Firebase 4 names (FIRApp, FIRMessaging, FIRInstanceID). Current Firebase uses FirebaseApp.configure(), Messaging, and Messaging.messaging().token. The app delegate must conform to UNUserNotificationCenterDelegate. token()! crashes when the token is still nil. connectToFcm() is defined below.

  1. If you don’t have an Xcode project yet, create one. Create a Podfile if you don’t have one:
cd your-project-directory
pod init
  1. Add the pods:
pod 'Firebase/Core'
pod 'Firebase/Messaging'
  1. Install the pods and open the workspace:
pod install
open your-project.xcworkspace
  1. Download a GoogleService-Info.plist file from the Firebase console and add it to the app.

  2. Upload an APNs certificate to Firebase. See APNs certificates.

  3. Add import Firebase in the app delegate.

  4. Call FIRApp.configure() in application:didFinishLaunchingWithOptions:.

  5. Register for remote notifications. UNUserNotificationCenter.current() is the Swift name. There is no currentNotificationCenter() method in Swift.

if #available(iOS 10.0, *) {
    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { _, _ in }

    // For iOS 10 display notification (sent via APNS)
    UNUserNotificationCenter.current().delegate = self
    // For iOS 10 data message (sent via FCM)
    FIRMessaging.messaging().remoteMessageDelegate = self
} else {
    let settings = UIUserNotificationSettings(forTypes: [.alert, .badge, .sound], categories: nil)
    application.registerUserNotificationSettings(settings)
}

application.registerForRemoteNotifications()
  1. Read the registration token:
let token = FIRInstanceID.instanceID().token()!
  1. To watch for token changes, add this to the app delegate. The method is not registered as an observer on this page.
func tokenRefreshNotification(notification: NSNotification) {
    if let refreshedToken = FIRInstanceID.instanceID().token() {
        print("InstanceID token: \(refreshedToken)")
    }

    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
}
  1. To receive a message, 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.")
        }
    }
}
  1. Disconnect when the app enters the background. This method name is Swift 2.
func applicationDidEnterBackground(application: UIApplication) {
    FIRMessaging.messaging().disconnect()
    print("Disconnected from FCM.")
}

After this initialization, the client can receive a message from the FCM console or from a server that sends to the token.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents