Не удалось подтвердить номер телефона - Flutter (ТОЛЬКО iOS) - PullRequest
0 голосов
/ 29 мая 2020

Я реализую проверку телефона OTP через Firebase Authentication с Flutter. На Android он работает как шарм , но с другой стороны на iOS Я не могу заставить его работать . Это ошибка, которую я получаю:

Обратите внимание, что я использую OneSignal, и он отлично работает как на Android, так и iOS

flutter: Ошибка проверки номера телефона. Код: verifyPhoneNumberError. Сообщение: Если переключение делегата приложения отключено, удаленные уведомления, полученные UIApplicationDelegate, должны быть перенаправлены на метод canHandleNotificaton: FIRAuth.

My flutter doctor:

enter image description here

Мои CocoaPods:

enter image description here

Моя функция OPT на Flutter:

import 'package:firebase_auth/firebase_auth.dart';

class SMSFunctions {
  /// Sends the code to the specified phone number.
  static Future<void> sendCodeToPhoneNumber(
      String phoneNo, Function onSuccess, Function onFailed) async {
    FirebaseAuth.instance.signOut();

    final PhoneVerificationCompleted verificationCompleted =
        (AuthCredential user) {
      print(
          'Inside _sendCodeToPhoneNumber: signInWithPhoneNumber auto succeeded: $user');
    };

    final PhoneVerificationFailed verificationFailed =
        (AuthException authException) {
      print(
          'Phone number verification failed. Code: ${authException.code}. Message: ${authException.message}');
      onFailed();
    };

    final PhoneCodeSent codeSent =
        (String verificationId, [int forceResendingToken]) async {
      verificationId = verificationId;
      print("code sent to " + phoneNo);
      onSuccess(verificationId);
    };

    final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
        (String verificationId) {
      verificationId = verificationId;
      print("time out");
      onFailed();
    };

    await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: phoneNo,
        timeout: const Duration(seconds: 5),
        verificationCompleted: verificationCompleted,
        verificationFailed: verificationFailed,
        codeSent: codeSent,
        codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
  }

  static Future<bool> confirmSMS(String smsCode, String verificationId) async {
    print(smsCode);
    print(verificationId);
    final AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: verificationId,
      smsCode: smsCode,
    );
    AuthResult authResult;
    try {
      authResult = await FirebaseAuth.instance.signInWithCredential(credential);
      print(authResult.user);
      final FirebaseUser currentUser = authResult.user;
      if (currentUser != null)
        return true;
      else
        return false;
    } catch (e) {
      print(e);
    }
    return false;
  }
}

Версия плагина:

firebase_auth: ^0.16.1

Это мои попытки:

  1. Изменен мой AppDelegate.swift, как в этом сообщении

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Pass device token to auth
    Auth.auth().setAPNSToken(deviceToken, type: .prod)

  }

  func application(_ application: UIApplication,
      didReceiveRemoteNotification notification: [AnyHashable : Any],
      fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if Auth.auth().canHandleNotification(notification) {
      completionHandler(.noData)
      return
    }
    // This notification is not auth related, developer should handle it.
  }

  // For iOS 9+
  func application(_ application: UIApplication, open url: URL,
      options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
    if Auth.auth().canHandle(url) {
      return true
    }
    // URL not auth related, developer should handle it.
  }

  // For iOS 8-
  func application(_ application: UIApplication,
                  open url: URL,
                  sourceApplication: String?,
                  annotation: Any) -> Bool {
    if Auth.auth().canHandle(url) {
      return true
    }
    // URL not auth related, developer should handle it.
  }

  func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    for urlContext in URLContexts {
        let url = urlContext.url
        Auth.auth().canHandle(url)
    }
    // URL not auth related, developer should handle it.
  }

  func application(_ application: UIApplication,
                  didReceiveRemoteNotification notification: [AnyHashable : Any],
                  fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if Auth.auth().canHandleNotification(notification) {
        completionHandler(.noData)
        return
    }
    // This notification is not auth related, developer should handle it.
    handleNotification(notification)
  }



}

Пытался изменить версию плагина FirebaseAuth, как в этом сообщении

Изменены мои URLSCHEMES, как в этом сообщении

My google.services-info.plist (скопирована желтая полоса) enter image description here

СХЕМЫ URL-адресов my info.plist (вставлена ​​желтая полоса) // Обратите внимание, что второй элемент - это Facebook URL-СХЕМА my URLSCHEMES

Изменил мой FirebaseAppDelegateProxyEnabled, как в этом сообщении

enter image description here

Настроил ключ аутентификации Firebase APNs и проверку reCAPTCHA в соответствии с Документами Google

enter image description here

enter image description here

Настроил мою подпись и возможности на Xcode

enter image description here

1 Ответ

0 голосов
/ 10 июля 2020

У меня была точная проблема, и я внес некоторые изменения, и она исправлена ​​с помощью приведенного ниже кода.

AppDelegate.swift

import UIKit
import Flutter
import Firebase
import FirebaseAuth
import UserNotifications
import FirebaseInstanceID

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
        FirebaseApp.configure()
        GeneratedPluginRegistrant.register(with: self)
        if #available(iOS 10.0, *) {
          UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
        }
        return true
  }
    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let firebaseAuth = Auth.auth()
        firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.unknown)

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

    }
}

Info.plist Я добавил строки ниже

<key>FirebaseAppDelegateProxyEnabled</key>
<false/>

Я получил ссылку по приведенной ниже ссылке. [https://pub.dev/packages/firebase_messaging] [1]

...