我有一个处于分段控制之下的表视图,该表视图的数据是从Firebase数据库中检索的,下面是代码:
func retrieveParticipatedData(completion: @escaping (Bool) -> Void) {
let storyIDRef = DBRef.child("Story IDs").child(userID!)
var participatedStoryItems: [ParticipatedStoriesPageData] = []
storyIDRef.observeSingleEvent(of: .value) { (snapshot) in
if let dict = snapshot.value as? [String : String] {
for (_, value) in dict {
self.DBRef.child("To be reviewed stories").child(value).observeSingleEvent(of: .value) { (snapshot) in
if let storyDict = snapshot.value as? [String : Any] {
let storyTitle = storyDict["Book Title"] as? String
let storyDescription = storyDict["Description"] as? String
let storyID = value
let votes = storyDict["Votes"] as? Int
let story = ParticipatedStoriesPageData(storyKey: storyID, storyTitle: storyTitle!, storyDescription: storyDescription!, votes: votes!)
participatedStoryItems.append(story)
}
self.participatedStories = participatedStoryItems
completion(true)
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
retrieveParticipatedData { (isRetreived) in
if isRetreived {
self.tableView.isHidden = false
self.tableView.reloadData()
}
}
}
数据检索没有问题。最初隐藏了表视图和分段控件,并且一旦检索到数据,便取消隐藏它们。
问题是表格视图中的数据不会立即显示,我必须转到另一个选项卡然后返回(我的分段控件中有2个选项卡),然后数据才显示在表格视图。我还添加了数据库图片。
这是我在Matt的帮助下尝试的内容:
func retrieveParticipatedData() {
let dispatchGroup = DispatchGroup()
let storyIDRef = DBRef.child("Story IDs").child(userID!)
var participatedStoryItems: [ParticipatedStoriesPageData] = []
storyIDRef.observeSingleEvent(of: .value) { (snapshot) in
if let dict = snapshot.value as? [String : String] {
for (_, value) in dict {
self.DBRef.child("To be reviewed stories").child(value).child("Participants").child("Chapter 1 Author").observeSingleEvent(of: .value) { (snapshot) in
if snapshot.value as? String == self.userID {
dispatchGroup.enter()
self.DBRef.child("To be reviewed stories").child(value).observeSingleEvent(of: .value) { (snapshot) in
if let storyDict = snapshot.value as? [String : Any] {
let storyTitle = storyDict["Book Title"] as? String
let storyDescription = storyDict["Description"] as? String
let storyID = value
let votes = storyDict["Votes"] as? Int
let story = ParticipatedStoriesPageData(storyKey: storyID, storyTitle: storyTitle!, storyDescription: storyDescription!, votes: votes!)
participatedStoryItems.append(story)
}
self.participatedStories = participatedStoryItems.reversed()
dispatchGroup.leave()
}
dispatchGroup.notify(queue: .main) {
print("Retrieved")
self.tableView.reloadData()
}
// It works if I do this
/*dispatchGroup.notify(queue: .main) {
print("Retrieved")
self.setupTableView // Creates the table view
}*/
//But I don't wanna do this cuz then there would be no table view if there is no data retreived.
}
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
retrieveParticipatedData()
setupStackView()
setupTableView() // Creates the table view
}
请让我尝试一下。不要隐藏表格视图,只需在viewDidLoad()中调用此函数即可。对于我的应用程序,我正在下载一长串用户,并使用分段控制器来加载个人资料照片的异步操作。我在这里可能是错的,因为我无法针对Firebase进行测试,但这与我正在执行的操作类似。