Swift显示Firebase重复数据(.observeChildAdded)无法正常工作

时间:2018-01-06 20:12:17

标签: swift firebase

每次我向数据库添加新帖子时,帖子显示的次数增加1。例如,当我添加一个新帖子时,帖子重复的次数是一次。当我添加另一个帖子(重新加载视图)时,我会看到所有帖子三次。我假设问题在于函数fetchPosts(),因为每次加载视图时,它都会收集来自firebase的所有数据并将其附加到数组中。我已经尝试在视图中清空数组并加载,但这只会使所有帖子显示更多次。此外,我尝试使用observe(.childAdded),结果根本没有显示帖子。

    var ref: DatabaseReference!
    var postList = [Post]()
    var refHandle : UInt!

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
        super.viewDidLoad()
        checkForSignedIn ()
        ref = Database.database().reference().child("posts")
        fetchPosts()

    }




    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return postList.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PostTableViewCell
        //set cell content
        let contentOfCellPost = postList[indexPath.row]
        cell.label?.text = contentOfCellPost.post_words
        cell.revealCount.text = contentOfCellPost.Reveals
        return cell
    }

public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let tableSize = tableView.bounds.height
    return tableSize
}


    func fetchPosts () {

        let query = ref.queryOrdered(byChild: "timestamp").queryLimited(toFirst: 10)

        query.observe(.value) { (snapshot) in

            for child in snapshot.children.allObjects as! [DataSnapshot] {
                if let value = child.value as? NSDictionary {
                        let post = Post()
                        let poster = value["poster"] as? String ?? "Name not found"
                        let post_content = value["post"] as? String ?? "Content not found"
                        let post_reveals = value["Reveals"] as? String ?? "Reveals not found"
                        post.post_words = post_content
                        post.poster = poster
                        post.Reveals = post_reveals
                        post.postID = child.key
                        self.postList.append(post)
                        print (post.post_words ?? "none")
                        DispatchQueue.main.async { self.tableView.reloadData() }
                        //make this for when child is added but so that it also shows psots already there something like query.observre event type of
            }
        }
    }
}

首先,控制台日志会显示正确的帖子数量: 三次 两次 一旦 TTTT BLOOP 十进制 9 7 3

当我添加新帖子时,它会显示: 黥 三次 两次 一旦 TTTT BLOOP 十进制 9 7 3 黥 三次 两次 一旦 TTTT BLOOP 十进制 9 7 3 黥 三次 两次 一旦 TTTT BLOOP 十进制 9 7 3 黥 三次 两次 一旦 TTTT BLOOP 十进制 9 7 3

1 个答案:

答案 0 :(得分:0)

您需要在.observe块的开头清除模型(self.postList),如下所示:

query.observe(.value) { (snapshot) in
    self.postList.removeAll() //or however you can clear it
        for child in snapshot.children.allObjects as! [DataSnapshot] {
            if let value = child.value as? NSDictionary {
                    let post = Post()
                    let poster = value["poster"] as? String ?? "Name not found"
                    let post_content = value["post"] as? String ?? "Content not found"
                    let post_reveals = value["Reveals"] as? String ?? "Reveals not found"
                    post.post_words = post_content
                    post.poster = poster
                    post.Reveals = post_reveals
                    post.postID = child.key
                    self.postList.append(post)
                    print (post.post_words ?? "none")
                    DispatchQueue.main.async { self.tableView.reloadData() }
                    //make this for when child is added but so that it also shows psots already there something like query.observre event type of
        }
    }

目前,每次使用帖子更新数据库时,都会再次向模型添加所有帖子。因此,每次获取所有帖子时都必须清除模型。

这在viewDidLoad中不起作用的原因是因为viewDidLoad在开始时只调用一次,而不是每次调用时都调用 - 因此在添加帖子时不会清除数据。

或者,您可以使用.childAdded - 但是您需要更改解析它的方式,因为每个带有.childAdded的快照都会返回一个帖子,而不是所有帖子。