【Swift/Firebase】Cloud Messagingのテスト通知方法!FCM登録トークン取得

この記事からわかること
- SwiftでFirebase Cloud Messagingのテスト通知方法
- FCM登録トークンの取得方法
index
[open]
\ アプリをリリースしました /
環境
- Xcode:15.0.1
- iOS:17.0
- watchOS:10.0
- Swift:5.9
- macOS:Sonoma 14.1
iOSアプリにFirebase Cloud Messagingを使用したリモートプッシュ通知のテストを実装する方法をまとめていきます、
Cloud Messagingのテスト通知方法
Cloud Messagingの「テスト通知」はあらかじめ決めたデバイスに対してのみ通知をテスト配信できる機能です。実際に配信するのではなく開発者が通知のテストを行うために利用されます。
この方法を使用することで実機を使用せずともシミュレーターでテストを行うことができるようになります。

テスト配信するにはiOSアプリとFirebase Cloud Messagingを連携させたFirebaseプロジェクトにアクセスし「Cloud Messaging」の画面に移動し、「最初のキャンペーンを作成」をクリックします。

配信できる通知は以下の2種類に分かれているので今回は上側の通知を配信してみます。

「通知のタイトル」と「通知テキスト」を入力し、右側にある「テストメッセージを送信」をクリックします。

すると以下の画面になり、テスト通知を配信するためには「FCM登録トークン」が必要になることがわかります。シミュレーターにも通知が届くようにするにはここに該当のFCM登録トークンを登録した状態で通知を公開する必要があります。

FCM登録トークンの取得方法
FCM登録トークンを取得するにはアプリにコードを組み込む必要があります。FirebaseMessaging
ライブラリを導入していない場合は組み込んでおいてください。
pod 'FirebaseMessaging'
UIKit(Storyboard)の場合
UIKit(Storyboard)でインターフェースを実装している場合は「AppDelegate.swift」に以下のようにコードを追記していきます。
import UIKit
import FirebaseCore
import FirebaseMessaging // 追加 #1
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self // #2
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: { _, _ in }
)
application.registerForRemoteNotifications()
return true
}
// 〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜
}
extension AppDelegate : UNUserNotificationCenterDelegate {}
// 追加
extension AppDelegate: MessagingDelegate {} // #3
追加したコード
- #1:FirebaseMessagingライブラリ
- #2:Messagingのデリゲート
- #3:拡張してMessagingDelegate
Messaging.messaging().tokenで取得処理
さらにAppDelegate
クラスにapplication(_:didRegisterForRemoteNotificationsWithDeviceToken)
メソッドを追加し、公式ドキュメントを参考に以下のコードを追記します。公式をそのまま引用するとfcmRegTokenMessage
が未定義なので削除しておきます。
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
print("FCM registration token: \(token)")
}
}
}
これで準備は完了したのでシミュレーターでアプリを実行し、デバッグエリアに表示される「FCM登録トークン(英数字の羅列)」をコピーしてFirebaseの入力欄にペーストすればテスト配信を行うことが可能です。

Swift UIの場合
Swift UIの場合は「プロジェクトApp.swift」に追加していきます。追加するものは基本的には同じになります。
import SwiftUI
import FirebaseCore
import GoogleMobileAds
import FirebaseMessaging
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: { _, _ in }
)
application.registerForRemoteNotifications()
GADMobileAds.sharedInstance().start(completionHandler: nil)
return true
}
}
extension AppDelegate : UNUserNotificationCenterDelegate {}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
print("FCM registration token: \(token)")
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
}
@main
struct プロジェクト名App: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
エラー:No APNS token specified before fetching FCM Token
Error Domain=com.google.fcm Code=505 "No APNS token specified before fetching FCM Token" UserInfo={NSLocalizedFailureReason=No APNS token specified before fetching FCM Token}
もしデバッグエリアに上記のようなエラーが発生していた場合は以下の記事を参考にしてみてください。
まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。
ご覧いただきありがとうございました。