【发布时间】: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