ios - Tableview 中的 Swift Firebase Firestore 数据

标签 ios swift uitableview firebase google-cloud-firestore

我在让 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/

相关文章:

ios - 多个文件下载任务的单个 ProgressView

ios - UITableView 滚动时滞后

iphone - 最终配置文件发送到设备

ios - Swift - MPMoviePlayerViewController 支持的设备方向

'HomePageVCNEW' 对协议(protocol) 'UITableViewDelegate' 的快速冗余一致性

xcode - 如何在 swift 中实例化 NSLayoutConstraint? (Xcode 6.1.1)

ios - 为 iOS 11 完全自定义 UINavigationBar

ios - 重新排序 tableviewcells,右侧白色 "bar"

ios - 如果我从可重用单元格的 super View 中删除 UILabel,重用时如何重新初始化单元格中的 UILabel?

ios - locationInView 忽略方向