繁体   English   中英

Tableview中的Swift Firebase Firestore数据

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM