我在让 tableView 加载来自 Firebase Firestore 的数据时遇到问题。我在 generateMore()
函数中迭代注释文档,并将添加注释作为 AttributedTextComment
分配给数组。但是当我在 View Controller 的 viewDidLoad() 中设置数组时,数组保持为空,我不明白为什么。谢谢你的帮助!另外,我正在使用 SwiftyComments 库,如果它可以帮助理解代码,可以在 Github 上找到它。
编辑:generateMore()
函数中的数组按预期填充了所有 Firestore 数据,但 ViewController 中的 allcomments
由于某种原因永远不会被设置为等于该数组。
class RandomDiscussion {
var comments: [AttributedTextComment]! = []
var colRef: CollectionReference!
func generateMore() -> [AttributedTextComment] {
var arr: [AttributedTextComment]! = []
colRef = Firestore.firestore().collection("pictures/TKIiXdontufmDM1idbVH/comments")
let query = colRef.whereField("body", isGreaterThan: "")
query.getDocuments() { (querySnapshot, err) in
if err != nil {
print("error")
return
}
else {
for doc in querySnapshot!.documents {
print("\(doc.documentID) => \(doc.data())")
let com = AttributedTextComment()
com.posterName = doc.get("username") as? String
com.body = doc.get("body") as? String
com.upvotes = doc.get("upvotes") as? Int
com.downvotes = doc.get("downvotes") as? Int
arr.append(com)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
}
}
}
return arr
}
}
class RedditCommentsViewController: CommentsViewController {
private let commentCellId = "redditComentCellId"
var allComments: [AttributedTextComment] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(RedditCommentCell.self, forCellReuseIdentifier: commentCellId)
tableView.backgroundColor = RedditConstants.backgroundColor
NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "load"), object: nil)
allComments = RandomDiscussion().generateMore()
currentlyDisplayed = allComments
self.swipeToHide = true
self.swipeActionAppearance.swipeActionColor = RedditConstants.flashyColor
}
override open func commentsView(_ tableView: UITableView, commentCellForModel commentModel: AbstractComment, atIndexPath indexPath: IndexPath) -> CommentCell {
let commentCell = tableView.dequeueReusableCell(withIdentifier: commentCellId, for: indexPath) as! RedditCommentCell
let comment = currentlyDisplayed[indexPath.row] as! RichComment
commentCell.level = comment.level
commentCell.commentContent = comment.body
commentCell.posterName = comment.posterName
//commentCell.date = comment.soMuchTimeAgo()
commentCell.upvotes = comment.upvotes
commentCell.isFolded = comment.isFolded && !isCellExpanded(indexPath: indexPath)
return commentCell
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.barTintColor = RedditConstants.flashyColor
self.navigationController?.navigationBar.tintColor = .white
UIApplication.shared.statusBarStyle = .lightContent
}
@objc func loadList(){
self.tableView.reloadData()
}
}
最佳答案
如果 Firebase 查询没有任何问题,则您的函数可能会失败。
将completionHandler与for语句和Firebase查询结合使用使事情变得更加容易。
将您的generateMore函数转换为:
func generateMore(completionHandler: @escaping (Bool, [AttributedTextComment]) -> Void) {
var arr: [AttributedTextComment]! = []
colRef = Firestore.firestore().collection("pictures/TKIiXdontufmDM1idbVH/comments")
let query = colRef.whereField("body", isGreaterThan: "")
query.getDocuments() { (querySnapshot, err) in
if err != nil {
print("error")
completionHandler(false, [])
}
else {
for doc in querySnapshot!.documents {
print("\(doc.documentID) => \(doc.data())")
let com = AttributedTextComment()
com.posterName = doc.get("username") as? String
com.body = doc.get("body") as? String
com.upvotes = doc.get("upvotes") as? Int
com.downvotes = doc.get("downvotes") as? Int
arr.append(com)
}
completionHandler(true, arr)
}
}
}
用法:
override func viewDidLoad() {
super.viewDidLoad()
// ...
allComments = RandomDiscussion().generateMore { (success, comments) in
if success {
currentlyDisplayed = comments
self.tableView.reloadData()
// OR
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
}
}
//...
}
关于ios - Tableview 中的 Swift Firebase Firestore 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52463600/