import SwiftUI import Combine import FirebaseCore import FirebaseMessaging @main struct DebugNotificationApp: App { #if os(iOS) @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate #elseif os(watchOS) @WKApplicationDelegateAdaptor(AppDelegate.self) var delegate #endif var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @EnvironmentObject var delegate: AppDelegate var body: some View { if let currentFCMToken = self.delegate.currentFCMToken { Text(currentFCMToken) ShareLink(item: currentFCMToken) } else { Text("No FCM token") } } } @MainActor class AppDelegate: NSObject, ObservableObject, MessagingDelegate, UNUserNotificationCenterDelegate { @Published var currentFCMToken: String? func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { print("==== ↓ Firebase Cloud Messaging token ↓ ====\n\(fcmToken!)") self.currentFCMToken = fcmToken } func setUpNotification() { Task { let notificationCenter = UNUserNotificationCenter.current() try! await notificationCenter.requestAuthorization(options: [.alert, .sound]) notificationCenter.delegate = self } } } #if os(iOS) extension AppDelegate: UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { FirebaseApp.configure() Messaging.messaging().delegate = self self.setUpNotification() application.registerForRemoteNotifications() return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {} } #elseif os(watchOS) extension AppDelegate: WKApplicationDelegate { func applicationDidFinishLaunching() { FirebaseApp.configure() Messaging.messaging().delegate = self self.setUpNotification() WKApplication.shared().registerForRemoteNotifications() } func didRegisterForRemoteNotifications(withDeviceToken deviceToken: Data) { Messaging.messaging().apnsToken = deviceToken } } #endif