所以我有一个tableView,它有一个标题元素和一些单元格。我从服务器中拉出单元格,然后在完成后重新加载tableview。那么这至少就是目前我在每个追加到数组后重新加载tavleView。我最终只想在所有数据基本拉出一次后才重新加载。函数
self.fetchEventsFromServer()
处理拉取数据的工作。我读了dispatchGroups并认为这是正确的方法,但我不知道如何去做。
import UIKit
import Firebase
class FriendsEventsView: UITableViewController{
var cellID = "cellID"
var friends = [Friend]()
var followingUsers = [String]()
//label that will be displayed if there are no events
var currentUserName: String?
var currentUserPic: String?
var currentEventKey: String?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Friends Events"
view.backgroundColor = .white
// Auto resizing the height of the cell
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "close_black").withRenderingMode(.alwaysOriginal), style: .done, target: self, action: #selector(self.goBack))
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
fetchEventsFromServer { (error) in
if error != nil {
print(error)
return
} else {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
@objc func goBack(){
dismiss(animated: true)
}
override func numberOfSections(in tableView: UITableView) -> Int {
print(friends.count)
return friends.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return friends[section].collapsed ? 0 : friends[section].items.count
return 1
}
func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
cell.textLabel?.text = "Something to fill Section: \(indexPath.section) Row: \(indexPath.row)"
return cell
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") as? CollapsibleTableViewHeader ?? CollapsibleTableViewHeader(reuseIdentifier: "header")
print(section)
header.arrowLabel.text = ">"
header.setCollapsed(friends[section].collapsed!)
print(friends[section].collapsed!)
header.section = section
// header.delegate = self
header.friendDetails = friends[section]
return header
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
func fetchEventsFromServer(_ completion: @escaping (_ error: Error?) -> Void ){
//will grab the uid of the current user
guard let myUserId = Auth.auth().currentUser?.uid else {
return
}
let ref = Database.database().reference()
//checking database for users that the current user is following
ref.child("following").child(myUserId).observeSingleEvent(of: .value, with: { (followingSnapshot) in
//handling potentail nil or error cases
guard let following = followingSnapshot.children.allObjects as? [DataSnapshot]
else {return}
//validating if proper data was pulled
for followingId in following {
print(followingId.key)
ref.child("users").child(followingId.key).observeSingleEvent(of: .value, with: { (userInfoSnapShot) in
guard let followingUserInfo = userInfoSnapShot.children.allObjects as? [DataSnapshot] else {
return
}
//validating if proper data was pulled for each follower
for currentUserInfo in followingUserInfo {
if currentUserInfo.key == "username"{
self.currentUserName = currentUserInfo.value as! String
print(self.currentUserName)
var friend = Friend(friendName: self.currentUserName!, imageUrl: self.currentUserPic!)
self.friends.append(friend)
}
if currentUserInfo.key == "profilePic"{
self.currentUserPic = currentUserInfo.value as! String
print(self.currentUserPic)
}
}
}, withCancel: { (err) in
completion(err)
print("Couldn't grab info for the current list of users: \(err)")
})
completion(nil)
}
}) { (err) in
completion(err)
print("Couldn't grab people that you are currently following: \(err)")
}
completion(nil)
}
}
关于我如何快速完成这件事的任何想法真的让我烦恼
Snapshot of following strucutre
"following" : {
"Iwr3EWqFBmS6kYRjuLW0Pw0CRJw2" : {
"CW1AIDxM43Ot3C1GtsyhQ0Zzwof2" : true
},
"OYWgNjYHEtX6EatkolPO5YXt6Rw2" : {
"nlSbmr1CXPbtuaUALNnftdHrbSt1" : true,
"qYSDao0zhFbLrzd0IJBafi7qdis2" : true
},
"nRrGzLFt3TeN4OOrwTe0RjHQoF13" : {
"CW1AIDxM43Ot3C1GtsyhQ0Zzwof2" : true,
"XV62sIs7anaGaoo0Wr9kooC8FDP2" : true,
"r51UQXn4Q2WcPWIhXIG3dhZTHkX2" : true
},
"nbmheFEPmBerm5avZwnriGJkaK12" : {
"nlSbmr1CXPbtuaUALNnftdHrbSt1" : true
},
"nlSbmr1CXPbtuaUALNnftdHrbSt1" : {
"OYWgNjYHEtX6EatkolPO5YXt6Rw2" : true,
"qYSDao0zhFbLrzd0IJBafi7qdis2" : true
},
"qYSDao0zhFbLrzd0IJBafi7qdis2" : {
"nlSbmr1CXPbtuaUALNnftdHrbSt1" : true
},
"wdciX8B2LeUy2NyDwU5cjLog5xx2" : {
"72297UgQllfrEaAQnUCPKuQMv933" : true,
"nbmheFEPmBerm5avZwnriGJkaK12" : true
}
}
答案 0 :(得分:2)
您希望向func fetchEventsFromServer()
功能添加完成处理程序,并在完成后调用reloadData()
。
func fetchEventsFromServer(_ completion: @escaping (_ error: Error?) -> Void ) {
.........
withCancel: { (err) in
completion(err)
print("Couldn't grab info for the current list of users: \(err)")
})
} completion(nil) // Right here I would think
}) { (err) in
}
然后当你打电话
fetchEventsFromServer { (error) in
if error != nil {
print(error)
return
} else {
self.tableView.reloadData()
}
}
此外,您不需要将self.
添加到代码中添加的许多内容中。只有当它嵌套在闭包和类似的东西中时。
答案 1 :(得分:1)
这是一个非常简化的示例作为指南(我的20循环是任意的,只有一个例子):
let group = DispatchGroup()
for _ in 0...20
{
group.enter()
// Do your server call and in it's completion block call..
group.leave()
}
let result = group.wait(timeout: .now() + 60)
基本思路是创建组,在你的for循环开始时“输入”组,每次从服务器得到响应你“离开”组,然后在循环之外“等待” “命令基本上会阻止方法继续,直到你”离开“你进入群组的次数(或者你花了太长时间)。
注意 - 由于这将阻塞它所在的线程,你绝对不希望在viewDidLoad中执行此操作,因为它将锁定整个UI,直到收到所有数据。在一个非主线程中解决这个问题。
答案 2 :(得分:1)
如果您事先不知道您的数据应该更新多少次(您将拥有多少条记录),您可以使用debouncer
而不是每次调用reloadData
时间。对于debouncer
实施,请查看How can I debounce a method call?
例如,您可以使用此答案https://stackoverflow.com/a/40634366/7132300
let debouncedFunction = debounce(interval: 500, queue: DispatchQueue.main, action: { (_: String) in
self.tableView.reloadData()
})
然后拨打debouncedFunction("dummy")
而不是reloadData
。您可以根据需要调整timeout
参数。