简体   繁体   English

Firebase 重新验证线程 1:致命错误:在隐式展开可选值错误时意外发现 nil

[英]Firebase Re-Authenticate Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value error

The user needs to be authenticated again to change the email address.用户需要重新进行身份验证才能更改电子邮件地址。 When I write the following code, I get the error: user.reauthenticate (with: credential) {_ in the line of error Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value.当我编写以下代码时,出现错误:user.reauthenticate (with: credential) {_ 在错误线程 1 的行中:致命错误:在隐式展开可选值时意外发现 nil。

var credential: AuthCredential! var 凭据:AuthCredential! I have also defined this我也定义了这个

 if let user = Auth.auth().currentUser {
            // re authenticate the user
            user.reauthenticate(with: credential) { _,error in
                if let error = error {
                    print(error)
                } else {
                    // User re-authenticated.
                    user.updateEmail(to: self.emailField.text!) { (error) in

                    }
                }
            }
        }

Xcode 截图

You need to prompt the user for their credentials, otherwise that property will be nil which will show the error you are seeing您需要提示用户输入他们的凭据,否则该属性将为 nil,这将显示您看到的错误

let user = Auth.auth().currentUser
var credential: AuthCredential

// *** Prompt the user to re-provide their sign-in credentials ***
//     populate the credential var with that data so it's not nil
//
user?.reauthenticate(with: credential) { error in
  if let error = error {
    // An error happened.
  } else {
    // User re-authenticated.
  }
}

You can follow this example step by step你可以按照这个例子一步一步

Configuration:配置:

-> Select your project -> 选择你的项目

-> Go to TARGETS -> 转到目标

-> Select your project icon - >选择你的项目图标

-> Click info tab - >点击信息标签

-> Add new URL Types(REVERSED_CLIENT_ID from GoogleService-Info.plist) -> 添加新的 URL 类型(来自 GoogleService-Info.plist 的 REVERSED_CLIENT_ID)

1. You need to setup your pre requisite configuration into your AppDelegate class


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

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

// 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.
    return ApplicationDelegate.shared.application(application, open: url)
}

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


2. It's your ViewModel class


class FirebaseSignin: NSObject {
    public func firebaseSigninWith(phoneNumber: String?, completion: @escaping (Bool, String?, Error?)->()) {
        //SVProgressHUD.show()
        if let phoneNumber = phoneNumber {
            print("firebaseSigninWith phoneNumber: ", phoneNumber)
            Auth.auth().languageCode = "fr";
            PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { [weak self] (verificationID, error) in
                //SVProgressHUD.dismiss()
                if let error = error {
                    completion(false, verificationID, error)
                    return
                }else{
                    UserDefaults.standard.set(verificationID, forKey: "authVerificationID")
                    completion(true, verificationID, error)
                }
            }
        }else{
            completion(false, nil, nil)
        }
    }

    public func otpConfirmation(verificationCode: String?, completion: @escaping (Bool, Any?, Error?)->()) {
        //SVProgressHUD.show()
        if let verificationCode = verificationCode {
            if let verificationID = UserDefaults.standard.string(forKey: "authVerificationID") {
                let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID, verificationCode: verificationCode)
                Auth.auth().signIn(with: credential) { (authResult, error) in
                    //SVProgressHUD.dismiss()
                    if let error = error {
                        completion(false, verificationID, error)
                        return
                    }else{
                        completion(true, verificationID, error)
                    }
                }
            }else{
                completion(false, nil, nil)
            }
        }else{
            completion(false, nil, nil)
        }
    }
}


3. you call your submitBttonAction function from LoginClass

func submitBttonAction() {
        let mobile_no = mobileNumberTextField.getFormattedPhoneNumber(format: .E164)
        self.firebaseSignin.firebaseSigninWith(phoneNumber: mobile_no) { [weak self] (isSuccess, verificationID, error) in
            if isSuccess {
                //GlobalVariable.showToastWith(view: GlobalVariable.getRootViewController()?.view, message: "OTP send successfully.")
                //RootViewController.selectViewController(_viewController: .OTPConfrimationViewController, ["delegate": self])
                // you open your OTPConfrimationViewController
            }else{
                //GlobalVariable.showToastWith(view: GlobalVariable.getRootViewController()?.view, message: "OTP sending fail \(error?.localizedDescription ?? "")")
            }
        }
    }

4. confirm your OTP from TOPViewController class

func otpConfirmation()  {
    if let otp = self.otpTextField.text {
        self.firebaseSignin.otpConfirmation(verificationCode: otp) { [weak self] (isSuccess, authResult, error) in
            if isSuccess {
                //GlobalVariable.showToastWith(view: GlobalVariable.getRootViewController()?.view, message: "OTP varified successfully.")
                //self?.handleHeaderBackAction(nil)
                //self?.delegate?.otpConfrimationCallBack(isSuccess)
            }else{
                //GlobalVariable.showToastWith(view: GlobalVariable.getRootViewController()?.view, message: "OTP varification fail \(error?.localizedDescription ?? "")")
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在展开图像的可选值时意外发现 nil - Unexpectedly found nil while unwrapping an Optional value for image Firebase:重新验证云中的当前用户 Function - Firebase: Re-authenticate the current user inside a Cloud Function 在展开可选时发现 nil。 选项应该从firestore下载 - Found nil while unwrapping optional. Optionals should be downloaded from firestore 重新验证用户。 使用 Android 的 FirebaseUI 身份验证 - Re-authenticate a user. with FirebaseUI auth for Android 如何在不重新加载页面的情况下在 AD 上重新进行身份验证? - How to re-authenticate on AD without reloading page? GeneratedPluginConstraint,致命错误:找不到模块“firebase_auth”@import firebase_auth; - GeneratedPluginConstraint , Fatal error: module 'firebase_auth' not found @import firebase_auth; FIREBASE 致命错误:无法确定 Firebase 数据库 URL - FIREBASE FATAL ERROR: Can't determine Firebase Database URL 尝试在 firebase 中使用 google 对用户进行身份验证时出错 - Error when trying to authenticate users with google in firebase Google Assistant 使用服务进行身份验证并发送 SYNC 请求时出错 - Error while Google Assistant authenticate with service and send a SYNC request 如何修复 firebase“找不到命令”错误 - how to fix firebase "command not found" error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM