LoginSignup
1
0

【SwiftUI 開発RTA】Firebaseからリモートでプッシュ通知する

Posted at

前提条件

  • Xcodeセットアップ済み
  • Apple Developer Program(有料)登録済み
  • Google Firebase登録済み

Xcodeでプロジェクトを作成する

  1. Xcodeを起動する
  2. Create New Project...
  3. Multi Pratform > App > Next
  4. Project Name: RemotePushSample(例) > Next
  5. Source Control: チェック外す(任意) > Create
  6. プロジェクトができる

Remote Notificationを有効にする

  1. RemotePushSample(TARGETS) > Signing & Capabilities
  2. +Capabilityをクリック
  3. Push Notificationsを選択
  4. もう一度、+Capabilityをクリック
  5. Background Modesを選択
  6. Background ModesのRemote notificationsをチェックする
    スクリーンショット 2024-03-28 15.05.16.png

Firebaseでプロジェクトを作成する

  1. Firebaseを開く
  2. プロジェクトを追加
  3. プロジェクト名:RemotePushSample(例) > 続行
  4. アナリティクスのチェック外す(任意) > 続行
  5. プロジェクトが作成されました > 続行
  6. iOS+を選択
    スクリーンショット 2024-03-28 15.10.56.png
  7. AppleバンドルID: 以下で確認できる > アプリを登録
    スクリーンショット 2024-03-28 15.12.23.png
  8. GoogleService-Info.plistをダウンロード
  9. もう左上の×で閉じてOK

Firebase SDKをインポートする

  1. Xcodeに戻る
  2. File > Add Package Dependencies...
  3. 右上の検索欄に https://github.com/firebase/firebase-ios-sdk と入力
  4. firebase-ios-sdkを選択 > Add Package
  5. FirebaseMessagingのみ選択 > Add Package
  6. RemotePushSampleフォルダを右クリック > Add Files to "RemotePushSample"...
    スクリーンショット 2024-03-28 15.44.55.png
  7. ダウンロードしたGoogleService-Info.plistを選択 > Add
  8. RemotePushSample(TARGETS) > Infoに以下を追加
    ・FirebaseAppDelegateProxyEnabled Boolean -> NO

コーディング

RemotePushSampleApp.swift
import SwiftUI
import FirebaseCore
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()
        return true
    }
    
    // テスト通知に必要なFCMトークンを出力する
    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)")
          }
        }
    }
}
extension AppDelegate: MessagingDelegate {}
extension AppDelegate: UNUserNotificationCenterDelegate {}

@main
struct RemotePushSampleApp: App {
    @UIApplicationDelegateAdaptor var delegate: AppDelegate
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

実機で起動してFCMトークンを確認

  1. 実機を選択してビルド→実行
  2. 通知を許可しておく
  3. 起動後、コンソールを見るとtokenが出力されているので控える
    スクリーンショット 2024-03-28 15.50.42.png

APNs認証キーを作成する

  1. Apple Developer > Certificates, Identifiers & Profiles > Keys
  2. +ボタンをクリック
  3. Key Name: RemotePushSample(例)
  4. Apple Push Notifications service (APNs)をチェックする
    スクリーンショット 2024-03-28 16.11.47.png
  5. Continue > Register
  6. 認証ファイル(.p8)をダウンロードし、Key IDを控える
    スクリーンショット 2024-03-28 16.13.20.png

Firebaseに認証キーをアップロードする

  1. 設定アイコン > プロジェクトの設定
    スクリーンショット 2024-03-28 16.06.20.png
  2. Cloud Messaging > Apple アプリの構成 > APNs 認証キーをアップロード
    スクリーンショット 2024-03-28 16.15.47.png
  3. APNs認証キー: ダウンロードした.p8ファイル
  4. キーID: 認証キー作成時に控えたKey ID
  5. チームID: Apple Developerで確認
    スクリーンショット 2024-03-28 16.21.12.png
  6. アップロード

Firebaseで通知を送信

  1. 左のタブ > エンゲージメント > Messaging
    スクリーンショット 2024-03-28 16.25.02.png
  2. 最初のキャンペーンを作成
  3. Firebase Notification メッセージ > 作成
  4. 通知のタイトル: テスト通知(例)
  5. 通知テキスト: これはテストです。(例)
  6. テストメッセージを送信
  7. Xcodeのコンソールで控えたFCMトークンを入力 > + > テスト
  8. テストデバイスに通知が送信されることを確認する
  9. 次へ > ターゲット: アプリを選択する
  10. 次へ > スケジュール設定: 現在
  11. 次へ > 確認 > 公開
  12. 数分後、通知が来る

終わり

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0