Почему SignInWithPhoneNumber из @ @Compacitor-Firebase/Authentication не работает в Ionic App для iOS?IOS

Программируем под IOS
Ответить
Anonymous
 Почему SignInWithPhoneNumber из @ @Compacitor-Firebase/Authentication не работает в Ionic App для iOS?

Сообщение Anonymous »

Я разрабатываю приложение Ionic/Angular, используя библиотеку @capacitor-firebase/authentication для аутентификации пользователя по номеру телефона.
Я реализовал следующий метод для входа в систему с помощью номера телефона. у меня на службе:
public async signInWithPhoneNumber(options: SignInWithPhoneNumberOptions,
loading: HTMLIonLoadingElement
): Promise {
try {
console.log("Attempting to sign in with phone number:", options.phoneNumber);

const user = await FirebaseAuthentication.signInWithPhoneNumber(options);

console.log('Sign-in successful');
} catch (error) {
console.error('Error during phone number verification:', error);
} finally {
await loading.dismiss();
}
}

Мой конструктор сервиса:
constructor(private readonly ngZone: NgZone) {

FirebaseAuthentication.removeAllListeners().then(() => {

FirebaseAuthentication.addListener('phoneCodeSent', async (event) => {
this.ngZone.run(() => {
console.log("phoneCodeSent"+ event.verificationId);
});
});

FirebaseAuthentication.addListener(
'phoneVerificationCompleted',
async (event) => {
this.ngZone.run(() => {
console.log("phoneVerificationCompleted"+ event.user?.uid);
});
},
);

FirebaseAuthentication.addListener(
'phoneVerificationFailed',
async (event) => {
this.ngZone.run(() => {
console.log("phoneVerificationFailed"+ event.message);
});
},
);

});
}

Ожидаемое поведение
Я ожидаю, что вызов FirebaseAuthentication.signInWithPhoneNumber(options) Firebase отправит SMS code и SignInWithPhoneNumber(options) для возврата объекта с информацией о пользователе или идентификатором проверки, который я могу использовать для проверки кода SMS. Вкратце, ПОЗВОЛЬТЕ ПРОИЗОЙТИ НЕКОТОРОЕ СОБЫТИЕ.
Фактическое поведение
При запуске этого кода на устройстве iOS консоль Xcode регистрирует следующее:
⚡️ [log] - Attempting to sign in with phone number: +573218116768
⚡️ To Native -> FirebaseAuthentication signInWithPhoneNumber 110818811
⚡️ TO JS undefined
⚡️ [log] - Sign-in successful

Ответ от собственного уровня (TO JS) неопределенная , и ошибка не выбрана. Также Firebase не отправляет SMS -сообщение. Наконец, в конструкторе моего сервиса слушатели для всех возможных событий, созданных моим методом Firebaseauthentication.SignInWithPhonenumber (Options) , но в консоли ничего не напечатано, как если бы не произошло события
. Дополнительная информация
Конфигурация Firebase:

[*] Аутентификация телефона включена в консоли Firebase. < /Li>
Файл GoogleService-info.plist правильно настроен и синхронизируется
с проектом. < /Li>

< /ul>
среда: < /p>

Ionic: 8.x < /li>
angular: ^18 .x
[*]@концентрация-фарбаза/аутентификация: ^6.3.1
[*] Конденсатор: 6.x

Что я проверил: < /em> < /p>

[*] Конфигурация Firebase верна (кроме как для APNS, который я не настраивал, потому что я понимаю, что это не требуется для входа телефона). < /P>
< /li>
Телефон номер находится в международном формате.

[*] Плагины конденсатора установлены и синхронизируются правильно.
< /ul>
Вопросы ключей: < /em> < /p>

Что может вызвать SignInWithPhonEnumber < /code> Не генерируйте какое -либо событие, и Firebase не отправляет SMS -код? Работайте над iOS, даже если я использую только аутентификацию телефона? Чтобы помочь решить эту проблему.
отредактировано: (Дополнительная информация)
Приложение Degate: < /p>
import UIKit
import Capacitor
import FirebaseCore

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
return true
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
// Called when the app was launched with a url. Feel free to add additional processing here,
// but if you want the App API to support tracking app url opens, make sure to keep this call
return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
}

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
// Called when the app was launched with an activity, including Universal Links.
// Feel free to add additional processing here, but if you want the App API to support
// tracking app url opens, make sure to keep this call
return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
}

}

Подфайл:

require_relative '../../node_modules/@capacitor/ios/scripts/pods_helpers'

platform :ios, '13.0'
use_frameworks!

# workaround to avoid Xcode caching of Pods that requires
# Product -> Clean Build Folder after new Cordova plugins installed
# Requires CocoaPods 1.6 or newer
install! 'cocoapods', :disable_input_output_paths => true

def capacitor_pods
pod 'Capacitor', :path => '../../node_modules/@capacitor/ios'
pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios'
pod 'CapacitorFirebaseAuthentication', :path => '../../node_modules/@capacitor-firebase/authentication'
pod 'CapacitorApp', :path => '../../node_modules/@capacitor/app'
pod 'CapacitorCamera', :path => '../../node_modules/@capacitor/camera'
pod 'CapacitorHaptics', :path => '../../node_modules/@capacitor/haptics'
pod 'CapacitorKeyboard', :path => '../../node_modules/@capacitor/keyboard'
pod 'CapacitorPreferences', :path => '../../node_modules/@capacitor/preferences'
pod 'CapacitorStatusBar', :path => '../../node_modules/@capacitor/status-bar'
end

target 'App' do
capacitor_pods
# Add your Pods here
end

post_install do |installer|
assertDeploymentTarget(installer)
end


Подробнее здесь: https://stackoverflow.com/questions/793 ... doesnt-wor
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»