I have been trying to integrate MFA through firebase within my app but I am having many issues. Initially I had no crash but the sms would not send and I would get the following error If app delegate swizzling is disabled, remote notifications received by UIApplicationDelegate need to be forwarded to FIRAuth’s canHandleNotificaton: method. I then created an app delegate and I now get the following console log:
12.3.0 – [GoogleUtilities/AppDelegateSwizzler][I-SWZ001014] App Delegate does not conform to UIApplicationDelegate protocol. ✅ Firebase configured in App init ✅ All managers initialized ✅ AppDelegate setup complete ✅ Notification permission granted ✅ Auth listener established📱 APNs token received FirebaseAuth/Auth.swift:1593: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
The token is being received but is found to be nil.
import SwiftUI
import Firebase
import FirebaseAuth
import FirebaseCore
import UserNotifications
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
// ✅ Store the token until we can safely set it
private var pendingAPNsToken: Data?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
// Firebase is already configured in LocumLedgerApp.init()
// Set up notification delegate
UNUserNotificationCenter.current().delegate = self
// Request notification authorization for MFA
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
print("✅ Notification permission granted")
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
} else if let error = error {
print("❌ Notification permission error: \(error.localizedDescription)")
}
}
print("✅ AppDelegate setup complete")
return true
}
// ✅ This receives the APNs token from iOS
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print("📱 APNs token received: \(tokenString)")
// Store token and attempt to set it after a delay
self.pendingAPNsToken = deviceToken
// Wait a bit longer to ensure Auth is fully initialized
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
self?.setAPNsToken()
}
}
// ✅ Set the APNs token once Auth is ready
private func setAPNsToken() {
guard let token = pendingAPNsToken else { return }
Auth.auth().setAPNSToken(token, type: .unknown)
print("✅ APNs token set in Firebase Auth")
pendingAPNsToken = nil
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("❌ Failed to register for remote notifications: \(error.localizedDescription)")
}
// ✅ Handle incoming silent push (verification SMS from Firebase)
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping(UIBackgroundFetchResult) -> Void) {
print("📩 Remote notification received: \(userInfo)")
if Auth.auth().canHandleNotification(userInfo) {
print("✅ Firebase Auth handled the notification (MFA verification)")
completionHandler(.noData)
return
}
print("ℹ️ Notification not handled by Firebase Auth")
completionHandler(.noData)
}
// ✅ Handle notifications when app is in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("📩 Foreground notification received")
// For MFA silent notifications, don't show UI
completionHandler([])
}
}
I have added push notifications as well as background modes remote notifications and configured the APN keys within firebase console. How can I fix this error?