在Swift中使用Firebase返回语句错误 [英] Return Statement Error using Firebase in Swift

查看:97
本文介绍了在Swift中使用Firebase返回语句错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个连接到Firebase的函数,转到特定路径,然后为我提供了值.当我打印(snapshot.value)时,它给了我所需的值.当我调用该函数时,userProfile为空.我需要userProfile返回快照字符串.

I made a function that connects to firebase, goes to a specific path and then gives me the value. When I print(snapshot.value), it gives me the value I need. When I call the function, userProfile is empty. I need userProfile to return the snapshot String.

 func getUserData(uid: String) -> String{
   var _REF_USERNAME = FIRDatabase.database().reference().child("users").child(uid).child("profile").child("username")

     var userProfile = String()


    _REF_USERNAME.observe(.value, with: {(snapshot) in
        print("SNAP: \(snapshot.value)")
            userProfile = snapshot.value as! String

    })
    print(userProfile)
    return userProfile
}

推荐答案

Swift 3

您正在观察中的回调外部调用userProfile,因此它将在观察功能异步完成之前执行.回调一开始很难理解,但是一般的想法是您的代码不是从上到下依次运行的,并且代码的某些部分在后台线程中异步运行.

You are calling userProfile outside of the callback in observe, so it'll be executed before the observe functions completes asynchronously. Callbacks are difficult to understand at first, but the general idea is that your code does not run sequentially from top to down, and there are some parts of the code that are run asynchronously in a background thread.

要访问userProfile,必须像这样传递回调函数:

To get access to userProfile, you have to pass in a callback function just like that:

func observeUserProfile(completed: @escaping (_ userProfile: String?) -> ()) -> (FIRDatabaseReference, FIRDatabaseHandle) {

    let ref = _REF_USERNAME

    let handle = ref.observe(.value, with: {(snapshot) in
            if !snapshot.exists() { // First check if userProfile exists to be safe
                completed(nil)
                return
            }
            userProfile = snapshot.value as! String
            // Return userProfile here in the callback
            completed(userProfile)
    })
    // Good practice to return ref and handle to remove the handle later and save memory
    return ref, handle

然后您在传递回调函数的同时在外部调用此观察代码:

And you call this observe code outside while passing in the callback function like that:

let ref, handle = observeUserProfile(completed: { (userProfile) in
     // Get access to userProfile here
     userProfile
}

完成此观察器操作后,请停止观察它,以执行以下操作以节省内存:

And when you're done with this observer, stop it from observing to save memory by doing the following:

ref.removeObserver(withHandle: handle)

这篇关于在Swift中使用Firebase返回语句错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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