如何让应用等待Firebase请求完成 [英] How to make app wait until Firebase request is finished

查看:120
本文介绍了如何让应用等待Firebase请求完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的方法等到Firebase请求完成

I want my method to wait until Firebase request finished

uploadSingUpInfo 在Firebase请求完成之前返回,并且这对我来说是一个问题 - 某些方法返回nil。

uploadSingUpInfo returns before the Firebase request finishes, and this is a problem for me - some method returns nil.

static func uploadSingUpInfo(fullName:String,email:String,password:String)->String{
    rootRef = FIRDatabase.database().reference()
    var returnVlue="not valid"

    FIRAuth.auth()?.createUserWithEmail(email, password: password) { (user, error) in
        if (error != nil){
            returnVlue=(error?.userInfo["error_name"]) as! String
        }
        else{

            let newUser = [
                "username": fullName
            ]
            rootRef.childByAppendingPath("User")
                .childByAppendingPath((user?.uid)!).setValue(newUser)
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isLogin")
            NSUserDefaults.standardUserDefaults().setObject(email, forKey: "email")
            NSUserDefaults.standardUserDefaults().setObject(user?.uid, forKey: "user_ID")
            print(NSUserDefaults.standardUserDefaults().objectForKey("user_ID"))
            returnVlue="valid"

        }
    }

    return returnVlue

}


推荐答案

不要将Firebase用作返回值的函数 - 它违背了它的异步性质。

Don't use Firebase as functions that return values - it goes against it's asynchronous nature.

规划代码结构,允许Firebase执行它的任务然后在闭包(块)内转到下一步。

Plan code structure that allows Firebase to perform it's task and then within the closure (block) go to the next step.

例如:在你的代码中,将函数更改为不返回任何内容并在createUserBlock中作为最后一行而不是返回,调用下一个函数来更新你的UI。

For example: In your code, change the function to not return anything and within the createUserBlock, as the last line instead of return, call the next function to update your UI.

static func uploadSingUpInfo(fullName:String,email:String,password:String) {

    rootRef = FIRDatabase.database().reference()

    FIRAuth.auth()?.createUserWithEmail(email, password: password) { (user, error) in
        if (error != nil){
            showUserAnError(error)
        } else {

            let newUser = [
                "username": fullName
            ]
            rootRef.childByAppendingPath("User")
                .childByAppendingPath((user?.uid)!).setValue(newUser)
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isLogin")
            NSUserDefaults.standardUserDefaults().setObject(email, forKey: "email")
            NSUserDefaults.standardUserDefaults().setObject(user?.uid, forKey: "user_ID")
            print(NSUserDefaults.standardUserDefaults().objectForKey("user_ID"))
            continueLoginProcess()  //reload the ui or whatever step is next
        }
      }
    }

这篇关于如何让应用等待Firebase请求完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆