Firebase收听点赞次数的变化并将其显示在屏幕上

时间:2018-06-27 19:59:05

标签: ios swift firebase

当用户双击图像时,每个帖子的点赞(心)数将增加。 我尝试了这段代码,但没有按预期工作(例如,当我双击时,它将加载一个帖子,并用不同数量的点赞(例如,帖子1-1like,帖子1-2like,帖子1-3like)进行复制。如何在不重复帖子的情况下显示更新的点赞次数?(帖子1-显示X的点赞次数,其中X =增量)

func loadPosts() {
let ref = Database.database().reference()
ref.child("posts").observe(.childAdded) { (snapshot: DataSnapshot) in
    if  let dict = snapshot.value as? [String: Any] {
        guard let titleText = dict["title"] as? String else{return}
        let locationDetails = dict["location"] as! String
        let captionText = dict["caption"] as! String
        let photoUrlString = dict["photoUrl"] as! String
        let priceText = dict["price"] as! String
        let categoryText = dict["category"] as! String
        let usernameLabel = dict["username"] as! String
        let profileImageURL = dict["pic"] as! String
        let heartInt = dict["heart"] as! Int
        let timestampString = dict["timestamp"] as! String
        let post = Post(titleText: titleText, captionText: captionText, locationDetails: locationDetails, photoUrlString: photoUrlString, priceText: priceText,categoryText: categoryText, usernameLabel: usernameLabel, profileImageURL: profileImageURL, heartInt: heartInt, timestampString: timestampString)
        //append(post) to array
        self.posts.append(post)
        print(self.posts)
        self.collectionView.reloadData()

    }
}
}

func delayCompletionHandler(completion:@escaping (() -> ())) {
    let delayInSeconds = 0.5
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
        completion()
    }
}
//CollectionView
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
 cell.reloadEvents = {
    self.delayCompletionHandler {
    self.loadPosts()
    }
}
}

要检测另一个文件中的heartTapped:

@objc func heartTapped(){
        print(" I heart u")
        let ref = Database.database().reference()
        heartInt1 += 1
        ref.child("posts").child(timestamp).observeSingleEvent(of: .value, with: { (snapshot) in
            if let dic = snapshot.value as? [String : AnyObject]{
                var heartString = dic["heart"] as! Int
                heartString += 1
                ref.child("posts").child(self.timestamp).updateChildValues(["heart" : heartString])
            }
    })
    reloadEvents?()
}
}

2 个答案:

答案 0 :(得分:0)

对不起,我应该在loadPosts()中添加self.posts.removeAll() 解决了。​​

答案 1 :(得分:0)

您的解决方案是不正确的做法。当您处理数据库时,您必须进行大规模的思考,如果每秒吸引您的金·卡戴珊(Kim Kardashian)使用您的应用程序,那么会发生什么,为每个人加载和删除所有内容?听起来有效吗?

您需要找到一种方法来仅加载心数而不是全部内容,以获取心数。

一种解决方案是添加一个额外的子代if/else,然后再添加一个let piePrices = { blueberry: 2.25, strawberry: 1.5, pumpkin: 3, apple: 2 } let pieArr = ['blueberry', 'strawberry', 'pumpkin', 'apple'] let total = 0 let totalPrice = pieArr.map(pie => ({cartTotal: total += piePrices[pie]})) console.log(totalPrice),在那儿您将获得仅心数。