Initialize FCM in Swift
suggest changeThese 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.
- 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
- Add the pods:
pod 'Firebase/Core'
pod 'Firebase/Messaging'
- Install the pods and open the workspace:
pod install
open your-project.xcworkspace
-
Download a
GoogleService-Info.plistfile from the Firebase console and add it to the app. -
Upload an APNs certificate to Firebase. See APNs certificates.
-
Add
import Firebasein the app delegate. -
Call
FIRApp.configure()inapplication:didFinishLaunchingWithOptions:. -
Register for remote notifications.
UNUserNotificationCenter.current()is the Swift name. There is nocurrentNotificationCenter()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()
- Read the registration token:
let token = FIRInstanceID.instanceID().token()!
- 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()
}
- 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.")
}
}
}
- 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.