swift - 从 Firebase 闭包返回数据

标签 swift firebase firebase-realtime-database closures

<分区>

到目前为止,一旦用户登录,我就能够尽可能地填充我的文本标签。因此,一旦他们这样做,主页就会显示“欢迎 johndoe”(johndoe 是他们注册的用户名)。但是,我还有一个汉堡包样式的 TableView ,其中包含他们的个人资料信息,其中包含他们的用户名、位置和他们的个人资料图像。我在使用相同的用户名(即 johndoe)填充 TableView 中的用户名时遇到问题。

我尝试使用一个全局变量来保存用户名字符串,但我一直得到默认值“No Name”

var username : String = "No Name"

    func getUserName() {

    let databaseRef = Database.database().reference()

    guard let userID = Auth.auth().currentUser?.uid else { return }

    databaseRef.child("users").child(userID).observeSingleEvent(of: .value) { (snapshot) in
        let theUserName = (snapshot.value as! NSDictionary)["nameOfUser"] as! String
        self.username = theUserName
        self.nameOfUserLabel.text! = "Welcome \(self.username)"
        //this prints out the correct label by saying "Welcome johndoe"
    }
    print("The name of the user is: \(self.username)")
    //for example it would print out in the console: "No Name"

}

通过使用用户名值,我试图将其分配给我的个人资料项目 TableView :

func createProfileArray() -> [ProfileItems] {
    var tempProfileItems: [ProfileItems] = []

    let profileItem = ProfileItems(profileImage: UIImage(named: "defaultUser")!, nameTitle: username, location: "Toronto")

    tempProfileItems.append(profileItem)


    return tempProfileItems
}

但是,一旦加载了 tableview,它只会显示“No name”。目标是使用与欢迎标题标签上相同的用户名。

感谢任何帮助。谢谢!

最佳答案

您不能调用获取名称的方法是异步的 (observeSingleEvent),因此请查看它执行的实际顺序

guard let userID = Auth.auth().currentUser?.uid else { return } // 1

databaseRef.child("users").child(userID).observeSingleEvent(of: .value) { (snapshot) in
    let theUserName = (snapshot.value as! NSDictionary)["nameOfUser"] as! String
    self.username = theUserName
    self.nameOfUserLabel.text! = "Welcome \(self.username)" // 3
    //this prints out the correct label by saying "Welcome johndoe"
}
print("The name of the user is: \(self.username)") // 2

关闭完成后你总是会看到No Name

关于swift - 从 Firebase 闭包返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55893747/

相关文章:

ios - Swift:Apple Mach-O 链接器错误(文件对于架构 x86_64 而言太小)

ios - 如何使用 UITableview 部分的首字母而不是整个部分标签?

javascript - 如何将 ReactFire 与 React Native 结合使用

javascript - Firestore函数触发器不会触发

Firebase 托管 Webhook

ios - TestFlight 与 App Store 构建的钥匙串(keychain)不同吗?

swift - 这是 Xcode 中的错误还是程序员应该避免的做法?

android - 从 firebase 获取数据快照时出错 -> java.lang.NumberFormatException : Invalid int: ""

javascript - React Firebase 时间戳用法

ios - 向下滚动和向上滚动后 UITableViewCell 中的图像发生变化