Firebase Notifications
Firebase Notifications
のiOS10
での設定方法からメッセージを送る方法です。
Firebase
とAPN
の基礎的なことははしょります。
Podfile
に下記を追加します。
pod 'Firebase/Core'
pod 'Firebase/Messaging'
お約束の証明書(CSR)、秘密キー(.p12)とプロビジョニングファイルを作成します。
詳しくはこちら-> https://firebase.google.com/docs/cloud-messaging/ios/certs
.p12の登録
Firebaseコンソールのギアアイコン > Project settings > CLOUD MESSAGING
を選択します。
Development APNs certificate
から、作成した.p12
ファイルをアップロードします。
Xcode Push通知を有効化
Xcodeを起動します。Capabilities
を開き、Push Notifications
をYES
にします。
実機をXcodeに接続します。(シミュレータでは通知を受け取れません。)
Swift実装 (iOS10のみ対応)
リモート通知を登録し、通知を受け取るコードをAppDelegate
に実装します。
詳しくはこちら-> https://firebase.google.com/docs/notifications/ios/console-audience
import UIKit
import Firebase
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FIRApp.configure() // Firebase初期設定
// リモート通知 (iOS10のみ対応)
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ 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
application.registerForRemoteNotifications()
}
// アプリがバックグラウンドで通知を受け、ユーザが通知をタップしてアプリをフォアグランドにした時に呼ばれる
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
debugPrint("You tapped the message.")
let userInfo = response.notification.request.content.userInfo
// Print message ID.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%@", userInfo)
completionHandler()
}
フォアグランドの時に通知を受け取る場合、エクステンションでデリゲートを実装します。(iOS10)
import Foundation
import UserNotifications
import Firebase
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// アプリがフォアグランドの時に通知を受け取ると呼ばれる
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print message ID.
print("Now Fourground. Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%@", userInfo)
}
}
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("%@", remoteMessage.appData)
}
}
Firebaseコンソールから通知を送る
Firebaseのコンソールから、Notificationsを選択し、新規メッセージを作成します。
Advanced options
をクリックすると、Custom data
キーバリューを設定することができます。