ios - 为什么 Swift Firebase auth() 响应晚?

标签 ios swift firebase firebase-authentication

为什么 auth() 函数响应迟了?当 status 返回时,它总是返回函数开头定义的值。有没有办法用函数调用 auth() createUser?

func register(email: String, password: String) -> Dictionary<String, Any> {
    var status = ["stat": false] as Dictionary<String, Any>
    let handle = Auth.auth().createUser(withEmail: email, password: password) { (result, error) in
        if error != nil {
            status["stat"] = false
            status["statement"] = error!.localizedDescription as String
        } else {
            status["stat"] = true
        }
    }
    return status
}

The handle function returns before the end of the register function.

最佳答案

createUser 是一个异步方法,您可以延迟返回值直到createUser 完成,但这不是处理异步方法的最佳方式。

如果您为原始方法提供一个完成 block ,例如:

func register(email: String, password: String, completion: @escaping(([String: Any]) -> Void)) {
    var status: [String: Any] = ["stat": false]
    let handle = Auth.auth().createUser(withEmail: email, password: password) { (result, error) in
        if error != nil {
            status["stat"] = false
            status["statement"] = error!.localizedDescription as String
        } else {
            status["stat"] = true
        }

        completion(status)
    }
}

然后在任何其他地方,您可以确定 createUser 已完成其过程:

register(email: "email", password: "password") { status in
    // Now it's ready.
    print(status)
}

关于ios - 为什么 Swift Firebase auth() 响应晚?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59658589/

相关文章:

ios - 带有 StackView 的 ScrollView 和固定的页脚在外面

ios - iphone 设备上的 UIPopoverController 替代品

ios - 在 SpriteBuilder 中使对象出现在第 N 帧而不是第 0 帧

ios - ITMS-90809 : Deprecated API Usage -- Apple will stop accepting submissions of apps that use UIWebView APIs

swift - 在 subview 中更新 ObservableObject 的 @Published 变量

javascript - Firebase orderByChild 顺序不正确

ios - React Native: bundle 标识符不存在

ios - 委托(delegate)方法必须公开

firebase - 未处理的异常 : MissingPluginException(No implementation found for method getToken on channel plugins. flutter.io/firebase_messaging)

java - 在 Android 上执行 firebase 查询