flutter:电话身份验证失败 - 错误:令牌无效..稍后重试

use*_*484 4 firebase flutter

Firebase 电话身份验证可在模拟器中运行,但无法在真实设备中运行。

我已经在developer.apple.com中创建了一个apn密钥,并将其添加到firebase中并启用了后台模式并检查获取、进程和后台。

这是控制台打印出来的内容:

Runner[11345:2633540] GTMSessionFetcher invoking fetch callbacks, data {length = 252, bytes = 0x7b0a2020 22657272 6f72223a 207b0a20 ... 5d0a2020 7d0a7d0a }, error Error Domain=com.google.HTTPStatus Code=400 "(null)" UserInfo={data={length = 252, bytes = 0x7b0a2020 22657272 6f72223a 207b0a20 ... 5d0a2020 7d0a7d0a }, data_content_type=application/json; charset=UTF-8}
2021-10-29 22:07:22.273998+0300 Runner[11345:2633546] flutter: Invalid token.
2021-10-29 22:07:22.523814+0300 Runner[11345:2633540] [connection] nw_resolver_start_query_timer_block_invoke [C3.1] Query fired: did not receive all answers in time for www.googleapis.com:443
Run Code Online (Sandbox Code Playgroud)

我的颤振代码如下

      Future<void> verifyPhone() async {
    await _auth.verifyPhoneNumber(
      phoneNumber: _phoneNumber,
      verificationCompleted: (PhoneAuthCredential credential) async {
        await FirebaseAuth.instance.signInWithCredential(credential);
        final snackBar = SnackBar(content: Text("Login Success"));
        ScaffoldMessenger.of(context).showSnackBar(snackBar);
      },
      verificationFailed: (FirebaseAuthException e) {
        print(e.message);
        final snackBar =
            SnackBar(content: Text("verificationFailed ${e.message}"));
        ScaffoldMessenger.of(context).showSnackBar(snackBar);
      },
      codeSent: (String verficationId, int resendToken) {
        setState(() {
          codeSent = true;
          verId = verficationId;
        });
      },
      codeAutoRetrievalTimeout: (String verificationId) {
        setState(() {
          verId = verificationId;
        });
      },
      timeout: Duration(seconds: 60),
    );
  }
Run Code Online (Sandbox Code Playgroud)

AppDelegate.swift

import UIKit
import Flutter
import Firebase

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

Podfile

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'
platform :ios, '10.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
end
Run Code Online (Sandbox Code Playgroud)

信息表

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleDisplayName</key>
    <string>DOTHawala</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleLocalizations</key>
    <array>
        <string>en</string>
        <string>fa</string>
        <string>ar</string>
    </array>
    <key>CFBundleName</key>
    <string>dot_exchange</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>$(FLUTTER_BUILD_NAME)</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>com.googleusercontent.apps.768659512914-kgtssn20sbm0ioj47dnp8ekcgsgou7b8</string>
            </array>
        </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>$(FLUTTER_BUILD_NUMBER)</string>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>https</string>
        <string>http</string>
    </array>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    <key>UIBackgroundModes</key>
    <array>
        <string>fetch</string>
        <string>processing</string>
        <string>remote-notification</string>
    </array>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <false/>
</dict>
</plist>
Run Code Online (Sandbox Code Playgroud)

Ken*_*ata 5

我遇到了完全相同的问题,并解决了。

  1. 首先,确保它firebase_messaging已列在pubspec.yaml.

  2. 如果您为 Info.plist 设置了选项<key>FirebaseAppDelegateProxyEnabled</key> <false/>,则可以通过在 上添加此工具来解决ios/Runner/AppDelegate.swift。(或者可能只是<key>FirebaseAppDelegateProxyEnabled</key> <false/>从 Info.plist 中删除,它会很简单地解决。)

import UIKit
import Flutter
import FirebaseMessaging

@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)
  }
}
  //  this block
  override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // NOTE: For logging
    // let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    // print("==== didRegisterForRemoteNotificationsWithDeviceToken ====")
    // print(deviceTokenString)
    Messaging.messaging().apnsToken = deviceToken
  }
}
Run Code Online (Sandbox Code Playgroud)