我在我的应用程序中遇到了一个非常有趣的问题。在查看用户配置文件页面时,我的tableview中的数据被拉出并打印到控制台中,但问题是我的信息不会加载到我的tablecell中。
如果我要退出当前标签然后返回个人资料页面,我的数据将被加载。我正在使用firebase来提取我的信息。
我希望第一次查看页面时数据存在。
ProfileViewController
var cellId = "cell"
var userGames = [Game]()
var userCurrentGames = [Any]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(ProfileGameCell.self, forCellReuseIdentifier: cellId)
//I CALL MY FUNCTIONS UPON FIRST LOAD
getCurrentUser()
getUsersGames()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//I CALL FUCTIONS EVERY TIME THE VIEW LOADS INCASE DATA CHANGES
getCurrentUser()
getUsersInformation()
getUsersGames()
}
func getUsersGames() {
let ref = Database.database().reference()
let current = getCurrentUser()
//I FIND ALL THE GAMES IN THE USERS REF AND APPEND THEIR KEY TO THE ARRAY
ref.child("users").child(current).child("user games").observe(.value, with: {(snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
self.userCurrentGames = []
for snap in snapshot {
let gameKey = snap.key
print("SNAPSHOT DATAAA: \(gameKey)")
self.userCurrentGames.append(gameKey)
}
}
})
displayUsersGames()
}
func displayUsersGames() {
let ref = Database.database().reference()
self.userGames = []
//I FIND ALL THE GAMES AND APPEND THEM TO THE ACTUAL GAME ARRAY
for i in userCurrentGames {
ref.child("games").child("\(i)").observeSingleEvent(of: .value, with: { (gameSnap) in
if let gameDict = gameSnap.value as? Dictionary<String, AnyObject> {
let key = gameSnap.key
let game = Game(postKey: key, gameData: gameDict)
self.userGames.append(game)
self.tableView.reloadData()
}
})
}
}
表格视图功能
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let game = userGames[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? ProfileGameCell {
cell.adminButton.tag = indexPath.row
cell.configureUserGameCell(game: game)
return cell
} else {
return ProfileGameCell()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userGames.count
}
答案 0 :(得分:2)
问题非常明确:
observe
异步工作 - 稍后会返回结果 - 因此userCurrentGames
在调用displayUsersGames()
时为空。
解决方案是将displayUsersGames()
移至完成块
...
ref.child("users").child(current).child("user games").observe(.value, with: {(snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
self.userCurrentGames = []
for snap in snapshot {
let gameKey = snap.key
print("SNAPSHOT DATAAA: \(gameKey)")
self.userCurrentGames.append(gameKey)
}
self.displayUsersGames()
}
})
注意:
强制向下转动单元格
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! ProfileGameCell
代码不得崩溃。如果是这样,则会发现设计错误。