verifyPhoneNumber in Flutter/Firebase app not working (‘token mismatch’)

I’ve been trying to get ‘signinwithphonenumber’ working for DAYS now, but I just can’t seem to do it on iOS. It works fine on Android, but try as I might, I cannot get the iOS version to work.

This is how I sign-in to firebase:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Firebase
  await Firebase.initializeApp(
    name: '<app name>',
    options: DefaultFirebaseOptions.currentPlatform,
  ).then((_) {
    print("Firebase initialized successfully.");
  }).catchError((error) {
    print("Error initializing Firebase: $error");
  });

// Clear Firestore persistence here
  try {
    await FirebaseFirestore.instance.clearPersistence();
    print('Firestore persistence cleared.');
  } catch (e) {
    print('Error clearing Firestore persistence: $e');
  }

  // Set Firestore settings
  try {
    FirebaseFirestore.instance.settings = const Settings(
      persistenceEnabled: false,
      sslEnabled: false,
      cacheSizeBytes: Settings.CACHE_SIZE_UNLIMITED,
    );
    print('Firestore settings updated.');
  } catch (e) {
    print('Error setting up Firestore: $e');
  }

  globals.fbdb = FirebaseFirestore.instance;
  globals.fbauth = FirebaseAuth.instance;
  globals.fbs = FirebaseStorage.instance;

  // Run the app
  runApp(const <appname>());
}

This is where I try to verify the phone number:

  static Future<void> verifyPhoneNumber(String phoneNumber) async {
    await FirebaseMessaging.instance.getToken();

    print("+++ phoneNumber = ${phoneNumber}");
    await globals.fbauth.verifyPhoneNumber(
      phoneNumber: phoneNumber,
      verificationCompleted: (PhoneAuthCredential credential) async {
        // Auto-retrieve verification code
        print("Verification Complete has been triggered for some reason!");
      },
      verificationFailed: (FirebaseAuthException e) {
        // Verification failed
        print('+++ Verification failed. Error = ${e}');
      },
      codeSent: (String verificationId, int? resendToken) async {
        // Save the verification ID for future use
        print('got through to codeSent section');
      },
      codeAutoRetrievalTimeout: (String verificationId) {},
      timeout: Duration(seconds: 60),
    );
  }
}

And this always triggers the ‘verificationFailed’ section, with the error ‘Token mismatch’.

This is the AppDelegate.swift:

import UIKit
import Firebase
import Flutter
import FirebaseMessaging
import FirebaseAuth

@main
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        // Firebase initialization
        GeneratedPluginRegistrant.register(with: self)
        Messaging.messaging().delegate = self
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if Auth.auth().canHandleNotification(userInfo) {
            print(userInfo)
            return
        }
        completionHandler(.newData)
    }

    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.unknown)
    }
}

extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        print("Firebase registration token: (String(describing: fcmToken))")
    }
}

Flutter version = 3.24.3 <> Stable channel
Dart 3.5.3
Devtools 2.37.3

Xcode: Version 15.4 (15F31d)

Android Studio Koala Feature Drop | 2024.1.2

Mac mini M2 Pro – 32GB

Testing on an iPhone 13 (real device)

  • There are no compile issues
  • All the plugins are up to date (all the Firebase ones are the latest versions available)
  • The ‘firebase-options.dart’ file is set up and correct (checked)
  • The URL Type with the REVERSE_CLIENT_ID is correct
  • I’ve checked and double checked all the certificates from Apple, and the .p8 key has been re-generated about 4 times now just to ensure I wasn’t having some kind of blackout (!) when I was generating it or something
  • ‘Authentication’ on the Firebase console is set up with ‘Sign in with Google’, ‘Sign In with phone number’ and ‘sign in with email address and password’ – all of which are enabled.
  • The bundle names are all correct, as is the name of the Firebase app everywhere it’s referenced
  • I’ve switched the ‘Autogenerated Key for iOS’ in Google Cloud Platform to being locked to iOS applications
  • I’m a paid Apple Developer
  • The right provisioning profile is set up
  • The GoogleService-Info.plist is in the right place and all the content is correct
  • The Background modes in the ‘signing & capabilities’ section are set to ‘Background Fetch’ and ‘Remote Notifications’

This is from hours upon hours of scouring StackOverflow, reading and re-reading the documentation from Google, and doing everything I can think of to get this to work…

…but all the same code (exactly) works perfectly on Android.

HELP! I’m losing the will to live!

Recognized by Google Cloud Collective

Finally, I found the solution after a week of searching:

  1. Locate the file firebase_sdk_version.rb and modify the version to 11.2.0.
    Image of the file location

  2. Run:
    pod update FirebaseAuth Firebase

  3. Then:
    pod install

After that, run your app, and everything should work!

New contributor

Mohamed Dwedar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật