[英]Swift Firebase Firestore Data in Tableview
我無法讓我的tableView從Firebase Firestore加載數據。 我遍歷了generateMore()
函數中的注釋文檔,並將添加的注釋作為AttributedTextComment
分配給數組。 但是,當我在viewDidLoad()
為視圖控制器設置數組時,該數組保持為空,我無法弄清原因。 謝謝你的幫助! 我還使用了可以在Github上找到的SwiftyComments庫,如果它可以幫助理解代碼。
編輯 : 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查詢沒有任何問題,則您的功能可能會失敗。
將completeHandler與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)
}
}
//...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.