【问题标题】:Returning data from a Firebase Closure [duplicate]从 Firebase 闭包返回数据 [重复]
【发布时间】:2019-09-17 12:15:18
【问题描述】:

到目前为止,一旦用户登录,我就能够尽可能多地填充我的文本标签。因此,一旦他们这样做,主页就会显示“欢迎 johndoe”(johndoe 是他们注册的用户名)。但是,我也有一个汉堡风格的表格视图,其中包含他们的个人资料信息,其中包含他们的用户名、位置和个人资料图像。我在使用相同的用户名(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"

}

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

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”。目标是拥有与欢迎标题标签上相同的用户名。

感谢任何帮助。谢谢!

【问题讨论】:

  • 请查找“异步”。顺便说一句 - 一个名为 getXXX 的函数应该有某种返回值。您应该将该方法重命名为 loadUserName 或类似名称。
  • 当然,会更改名称。但是我到底该怎么处理异步呢?
  • 查找它的含义。我想 Firebase 文档会提到它。

标签: swift firebase firebase-realtime-database closures


【解决方案1】:

您不能对获取名称的方法的调用是异步的(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 在闭包完成

【讨论】:

    猜你喜欢
    • 2021-06-21
    • 2021-06-21
    • 1970-01-01
    • 2017-06-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    相关资源
    最近更新 更多