LoginSignup
4
2

More than 3 years have passed since last update.

SwiftUI ベースのプロジェクトでの FCM 実装注意点

Last updated at Posted at 2021-03-03

はじめに

基本的な実装方法・証明書周りの設定方法は日本語の記事も多いのでそちらをご覧ください。
https://firebase.google.com/docs/cloud-messaging/ios/client?hl=ja

今回は SwiftUI でプロジェクトを作成した場合、つまり AppDelegate を後から追加した場合の注意点をご紹介します。

結論

FCM SDK は deviceToken を取得する処理の実装を Method Swizzling を利用して実現しています。ただし、これが正常に動作するのは AppDelegate@main として利用している場合に限ります。
なので、 SDK の Method Swizzling に頼らず、以下の処理を明示的に記述する必要があります。

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

詳細

SwiftUI をベースにプロジェクトを作成した場合、以下のような形で AppDelegate を実装することになります。
この場合、 FCM SDK による Method Swizzling が AppDelegate に対して走らないため、開発者側で明示的に追記してあげる必要があります(ここの挙動は細かく調べたわけではないので、間違いがあればご指摘お願いします)

@main
struct MyApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ...
        }
    }
}

final class AppDelegate: UIResponder, UIApplicationDelegate {
    typealias LaunchOptionsKey = UIApplication.LaunchOptionsKey
    func application(_ application: UIApplication, didFinishLaunchingWithOptions: [LaunchOptionsKey: Any]? = nil) -> Bool {
        return true
    }
}

詳しくはここに記述されています。
実装入れ替えが無効な場合の APNs トークンと登録トークンとのマッピング

さいごに

結論として、公式ドキュメントにもしっかり書かれている内容だったということになりますが、 SwiftUI メインでアプリを開発する場合は特に注意したほうがいいかと思い、記事として残してみました。
公式ドキュメント・SDK ともに後々仕様が変わる可能性がありますので、まずは最新の情報を確認した上でこの記事も参考にしていただければと思います。

最後まで読んでいただき、ありがとうございます!

4
2
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
4
2