使用相同的UploadKey从帖子同步保持数据

时间:2017-06-06 16:02:43

标签: ios swift firebase firebase-realtime-database

我正在开发一个应用程序,您可以在其中发布不同类别的图片。 例如:动物/摩托车。

我的用户可以关注用户并查看他们的照片。

现在我正在开展以下工作:我想在一个类别中同时上传所有帖子中的帖子(一个单独的屏幕,用户可以随机查看所有发布的图片)

每个帖子,无论在哪里发布,都将在allPosts孩子中

var REF_POST = Database.database().reference().child("posts")

并且每个类别都有一个特定的孩子,其中只有此类别的帖子保留在

var REF_POST = Database.database().reference().child("motorcycles")

现在您可以在Feed中添加并发表评论而不会出现任何问题。 它使用来自孩子的数据" allPosts"

现在我想自动保持数据与摩托车中的帖子同步。它们都共享相同的密钥,但显然只能在" allPosts"子。

目标是始终根据" allPosts"中的数据更新每个类别。并反转。因此,如果用户喜欢该类别,它也会在" allPosts"中更新。

更新代码

func incrementLikesFeed(postId: String,  onSuccess: @escaping (Post) -> Void, onError: @escaping (_ errorMessage: String?) -> Void){
    let postRef = API.Post.REF_POSTS.child(postId)

    postRef.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
        if var post = currentData.value as? [String : AnyObject], let uid = API.User.CURRENT_USER?.uid {

            var likes: Dictionary<String, Bool>
            likes = post["likes"] as? [String : Bool] ?? [:]
            var likeCount = post["likeCount"] as? Int ?? 0
            var score = post["score"] as? Int ?? 0

            if let _ = likes[uid] {
                likeCount -= 1
                score -= 100
                likes.removeValue(forKey: uid)
                self.REF_LIKES_POSTS.child(postId).child(uid).removeValue()

            } else {

                likeCount += 1
                score += 100
                likes[uid] = true
                self.REF_LIKES_POSTS.child(postId).child(uid).setValue(true)
            }

            post["score"] = score as AnyObject?
            post["likeCount"] = likeCount as AnyObject?
            post["likes"] = likes as AnyObject?
            currentData.value = post

            return TransactionResult.success(withValue: currentData)
        }
        return TransactionResult.success(withValue: currentData)
    }) { (error, committed, snapshot) in
        if let error = error {
            print(error.localizedDescription)
            onError(error.localizedDescription)
        }
        if let dict = snapshot?.value as? [String: Any] {
            let post = Post.transformPost(dict: dict, key: snapshot!.key)
        onSuccess(post)
        }
    }

}
例如,这会更新所有帖子中的like节点。 由于我将有10个以上的类别,我希望始终更新特定数据库路径中的拟合帖子

示例:

database.database().reference.child("Text").child("shortJokes")
database.database().reference.child("allPosts") -> where all posts are

我怎样才能实现只有特定的孩子得到更新?

因为稍后我会像那样

database.database().reference.child("Text").child("Sport")
database.database().reference.child("Text").child("Animals")
database.database().reference.child("Pictures").child("funnyPictures")
database.database().reference.child("Pictures").child("sweetAnimals")

我希望它检查所有帖子中的整个数据库,以查看子项包含相同postId的位置。 我看到问题,当我有10个以上的类别时,我必须在一个中调用10个函数,并且它可能总是更新所有内容而不是只有一个具有相同id的帖子。

更新

            let newUserData = ["score": score, "likeCount": likeCount, "likes": likes] as [String : Any]

            let postRefEinzeiler = self.REF_EINZEILER.child(postId)
            postRefEinzeiler.updateChildValues(newUserData)

            let postRefSchwHumor = self.REF_SCHWARZERHUMOR.child(postId)
            postRefSchwHumor.updateChildValues(newUserData)

通过这段代码,我设法实现了我想要做的事情。 但是,它总是使用我提供的数据在其他类别中添加一个带有postId的节点。

如果postId已经存在且仅存在更新值,我怎么能首先查看它?

1 个答案:

答案 0 :(得分:1)

var BASE_POST = Database.database().reference()

// Generate a new push ID for the new post
let postkey = ENTER YOUR POST_ID 
let postData = YOUR_POST_DETAILS_DICTIONARY

// Create the data we want to update
let updatedPostData = ["posts/\(postkey)": postData, 
              "motorcycles/\(postkey)": postData ]


// Do a deep-path update
ref.updateChildValues(updatedPostData, withCompletionBlock: { (error, ref) -> Void in
    if (error) {
        print("Error updating data: \(error.description)")
    }
})