Вот как я вхожу в Firebase:< /p>
Код: Выделить всё
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize Firebase
await Firebase.initializeApp(
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 ());
}
Код: Выделить всё
static Future 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),
);
}
}
Это 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))")
}
}
Dart 3.5.3
Devtools 2.37.3
Xcode: Версия 15.4 (15F31d)
Дополнительная функция Android Studio Koala | 2024.1.2
Mac mini M2 Pro — 32 ГБ
Тестирование на iPhone 13 (реальное устройство)
- Проблем с компиляцией нет.
- Все плагины обновлены (все плагины Firebase — последние доступные версии).
- Файл Firebase-options.dart настроен и корректен (проверен).
- Тип URL с REVERSE_CLIENT_ID верен.
- Я проверил и дважды проверил все сертификаты Apple, и ключ .p8 был повторно сгенерирован примерно 4 раза, просто чтобы убедиться, что у меня не было какого-то отключения электроэнергии (!), когда я его генерировал или что-то в этом роде < /li>
Аутентификация на консоли Firebase настраивается с помощью «Войти с помощью Google», «Войти с помощью номера телефона» и «Войти с помощью адреса электронной почты и пароля» — все это включен. - Все имена пакетов верны, как и имя приложения Firebase везде, где оно упоминается.
- Я включил параметр «Автогенерируемый ключ». для iOS» в Google Cloud Platform для привязки к приложениям iOS.
- Я платный разработчик Apple.
- Настроен правильный профиль обеспечения< /li>
GoogleService-Info.plist находится в правильном месте, и все его содержимое правильное. - Фоновые режимы в разделе «подпись и возможности» указаны установлены значения «Фоновая выборка» и «Удаленные уведомления».
...но все равно код (точно) отлично работает на Android.
ПОМОГИТЕ! Я теряю желание жить!
Подробнее здесь: https://stackoverflow.com/questions/789 ... n-mismatch