从Firestore返回名称? [英] Returning name from Firestore?

查看:48
本文介绍了从Firestore返回名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Firestore上获取名称后,我试图返回一个名称,但由于某种原因,该名称无法正常工作.

I'm trying to return a name after getting it on Firestore, but for some reason it's not working.

这是我的代码:

func getName() -> String {

        var name = ""

        db.collection("users").whereField("email", isEqualTo: user.email!).getDocuments { (snapshot, error) in

            if error != nil {

                print(error!)

            } else {

                for document in (snapshot?.documents)! {

                    name = document.data()["name"] as! String
                    // if I add `print(name) here, it works.`
                }
            }
        }
        return name
    }

但是它返回一个空字符串:/我想返回实际名称.我该如何解决?

But it returns an empty string :/ I want to return the actual name. How do I fix this?

推荐答案

getDocuments 是异步函数.这意味着 name 变量在继续执行之前不会等待函数完成.如果要从文档返回返回的名称,可以查看以下代码:

getDocuments is an asynchronous function. This means the name variable doesn't wait for the function to complete before continue executing. If you want to return the returned name from the document, you can take a look at the following code:

 func getName(_ completion: (String) -> ()) {
    db.collection("users").whereField("email", isEqualTo: user.email!).getDocuments { (snapshot, error) in
        if error != nil {
            print(error!)
        } else {
            for document in (snapshot?.documents)! {
                name = document.data()["name"] as! String
                completion(name)
            }
        }
    }
}

getName { name in
    print(name)
}

这篇关于从Firestore返回名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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