アプリケーション開発ポータルサイト
ServerNote.NET
カテゴリー【iPhone/iPadMacOSGoogleSwift
FirebaseでiOSアプリにプッシュ通知機能を実装する【2】
POSTED BY
2024-03-15

FirebaseでiOSアプリにプッシュ通知機能を実装する【1】

続きです。通知通信のための証明書作成・登録はテスト・本番用それぞれ前回で終えたので、あとは段階を踏んで実装・テストするだけです。

Firebase SDKにてCloud Messagingの使用をオンにする

Podfileに追記します。

  1. pod 'FirebaseMessaging'

アップデート&インストールします。

  1. pod install --repo-update

これでソース中でimport FirebaseMessagingとして、コードを書けるようになるはずです。

CapabilityにPush NotificationsとBackground Modesを追加する

Xcodeでプロジェクト(xcworkspace)を開いて、左ペイン一番上プロジェクト名青アイコン→TARGETS→MyAppで、「Signing & Capabilities」を開きます。

気づきにくいですが左上あたりに「+Capability」があるので、ここで「Push Notifications」と「Background Modes」をそれぞれ追加します。そして「Background Modes」には、「Remote notifications」をチェックします。

プッシュ通知に対応するSwiftコードを書く

基本的にはAppDelegate.swiftに書きますが、ユーザーに通知の許可をもらうダイアログはアプリの他の適切な箇所のほうが良いです。

SwiftAppDelegatePushNotify.swiftGitHub Source
  1. import SwiftUI
  2. import FirebaseCore
  3. import FirebaseMessaging
  4. import UserNotifications
  5.  
  6. class AppDelegate: NSObject, UIApplicationDelegate {
  7. let gcmMessageIDKey = "gcm.message_id"
  8. func application(_ application: UIApplication, didFinishLaunchingWithOptions
  9. launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
  10. print("AppDelegate.application")
  11. FirebaseApp.configure()
  12. Messaging.messaging().delegate = self
  13. UNUserNotificationCenter.current().delegate = self
  14. let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
  15. UNUserNotificationCenter.current().requestAuthorization(
  16. options: authOptions,
  17. completionHandler: { _, _ in }
  18. )
  19. application.registerForRemoteNotifications()
  20. //application.applicationIconBadgeNumber = 0
  21. return true
  22. }
  23. func application(_ application: UIApplication,
  24. didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  25. print("AppDelegate.didReceiveRemoteNotification")
  26. if let messageID = userInfo[gcmMessageIDKey] {
  27. print("Message ID: \(messageID)")
  28. }
  29. print(userInfo)
  30. }
  31. func application(_ application: UIApplication,
  32. didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async
  33. -> UIBackgroundFetchResult {
  34. print("AppDelegate.didReceiveRemoteNotificationBackground")
  35. if let messageID = userInfo[gcmMessageIDKey] {
  36. print("Message ID: \(messageID)")
  37. }
  38. print(userInfo)
  39. return UIBackgroundFetchResult.newData
  40. }
  41. func application(_ application: UIApplication,
  42. didFailToRegisterForRemoteNotificationsWithError error: Error) {
  43. print("AppDelegate.didFailToRegisterForRemoteNotificationsWithError,error=\(error.localizedDescription)")
  44. }
  45. func application(_ application: UIApplication,
  46. didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  47. print("AppDelegate.didRegisterForRemoteNotificationsWithDeviceToken,deviceToken=\(deviceToken)")
  48. }
  49. }
  50.  
  51. // [START ios_10_message_handling]
  52. extension AppDelegate: UNUserNotificationCenterDelegate {
  53. func userNotificationCenter(_ center: UNUserNotificationCenter,
  54. willPresent notification: UNNotification) async
  55. -> UNNotificationPresentationOptions {
  56. print("AppDelegate.UNUserNotificationCenterDelegate.willPresent")
  57. let userInfo = notification.request.content.userInfo
  58. if let messageID = userInfo[gcmMessageIDKey] {
  59. print("Message ID: \(messageID)")
  60. }
  61. print(userInfo)
  62. return [[.banner, .badge, .sound]]
  63. }
  64. func userNotificationCenter(_ center: UNUserNotificationCenter,
  65. didReceive response: UNNotificationResponse) async {
  66. print("AppDelegate.UNUserNotificationCenterDelegate.didReceive")
  67. let userInfo = response.notification.request.content.userInfo
  68. if let messageID = userInfo[gcmMessageIDKey] {
  69. print("Message ID: \(messageID)")
  70. }
  71. print(userInfo)
  72. }
  73. }
  74. // [END ios_10_message_handling]
  75.  
  76. extension AppDelegate: MessagingDelegate {
  77. func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
  78. print("AppDelegate.MessagingDelegate.didReceiveRegistrationToken,fcmToken=\(String(describing: fcmToken))")
  79. let dataDict: [String: String] = ["token": fcmToken ?? ""]
  80. NotificationCenter.default.post(
  81. name: Notification.Name("FCMToken"),
  82. object: nil,
  83. userInfo: dataDict
  84. )
  85. }
  86. }
  87.  
  88. @main
  89. struct MyApp: App {
  90. @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
  91. var body: some Scene {
  92. WindowGroup {
  93. ContentView()
  94. }
  95. }
  96. }

ここではアプリ起動時にrequestAuthorizationしてユーザーに許可を促しています。

テストデバイストークンを取得してコピーしておく

このコードでアプリを実行すると、

  1. print("AppDelegate.didRegisterForRemoteNotificationsWithDeviceToken,deviceToken=\(deviceToken)")

または

  1. print("AppDelegate.MessagingDelegate.didReceiveRegistrationToken,fcmToken=\(String(describing: fcmToken))")

が呼ばれてそのデバイスのトークン文字列がデバッグエリアに出力されますので、それをコピーしておきます。

Firebase Messagingでテストメッセージを送信する

Firebaseコンソールを開いて、左ペインの「Messaging」を開き、Messagingのメイン画面にて「新しいキャンペーンを作成→通知」を開きます。

・端末上に表示される通知のタイトル、通知テキスト(本文)を入力します。
・「ターゲット」で、通知を送信するターゲットアプリを選択します。jp.co.mycorp.MyApp。
・「スケジュール設定」は今すぐ送信「現在」
・「その他のオプション」で通知音の有無、バッジの有無と数を指定できます。バッジありで数を指定した場合、アプリ側のアイコンの右上に未読の数が赤丸で出るあれです。

ここまで設定を終えたら「確認」ボタンを押さずに、「通知」に戻って「テスト メッセージの送信」を押します。ここで、「FCM 登録トークンを追加」とあるので、さきほど控えておいたデバイスのトークン文字列を貼り付けて登録し、チェックで選択して、「テスト」ボタンを押すと、即座に実行中のデバイス単体に通知が送信されます。

通知をタップすれば上記コードのAppDelegate.UNUserNotificationCenterDelegate.didReceiveが呼ばれますし、アプリが実行中で表示中であればAppDelegate.UNUserNotificationCenterDelegate.willPresentが呼ばれるはずです。そうなれば成功です。

※本記事は当サイト管理人の個人的な備忘録です。本記事の参照又は付随ソースコード利用後にいかなる損害が発生しても当サイト及び管理人は一切責任を負いません。
※本記事内容の無断転載を禁じます。
【WEBMASTER/管理人】
自営業プログラマーです。お仕事ください!
ご連絡は以下アドレスまでお願いします★

【キーワード検索】