Firebase クラウドメッセージサービスのインテグレーション

Firebaseは、グーグルが買収したベンチャー企業で、モバイルアプリの様々なプラットフォームを提供しています。各種サービスを提供していますが、今回の紹介は、無料サービスのCloud Messagingでモバイルアプリにメッセージを送ることができ、言語別、トピック別にメッセージを送付したり、送付するメセージのA/Bテストの機能もあります。

FireBaseの面白いところは、Googleが買収したので、Googleのユーザー属性に関するデータにアクセスして分析結果がダッシュボードに表示されます。iTunes Connectのアナリティックスでは表示されないユーザーの性別、年齢、国の長めのリスト、アクセスしたスクリーンクラス、興味分野などを知ることができます。

設定方法(iOS)

Xcodeを開いて、GoogleService-Info.plistをダウンロードリンクから追加します。

CocapodのPodfileの設定は

pod ‘Firebase/Core’
pod ‘Firebase/Messaging’

次にFirebaseのコンソールからAPNs authentication keyを取得し、これをiTunesConnectで使用

アプリでの初期化は

import Firebase

AppleDelegate.swift内でのRemote notificatioinの登録をします。

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()

FIRMessaging delegateを設定

Messaging.messaging().delegate = self

Registration Tokenを受け取るには

let token = Messaging.messaging().fcmToken

AppleDelegate.swift内でのToken 生成のモニタリング

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { print(“Firebase registration token: \(fcmToken)”)

// TODO: If necessary send token to application server. // Note: This callback is fired at each app startup and whenever a new token is generated.
}

APNSTokenのマッピング

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
Messaging.messaging().apnsToken = deviceToken
}

詳細は
https://firebase.google.com/docs/cloud-messaging/?authuser=0