Synchronized Array (for likes/followers) Best Practice [Firebase Swift]

倾然丶 夕夏残阳落幕 提交于 2019-11-30 10:24:59
Tim Lupo

Thanks to Frank, I figured out a solution using runTransactionBlock. Here it is:

static func follow(user: FIRUser, userToFollow: FIRUser) {
    self.database.child("users/"+(user.uid)+"/Following").runTransactionBlock({ (currentData: FIRMutableData!) -> FIRTransactionResult in
        var value = currentData?.value as? Array<String>
        if (value == nil) {
            value = [userToFollow.uid]
        } else {
            if !(value!.contains(userToFollow.uid)) {
                value!.append(userToFollow.uid)
            }
        }
        currentData.value = value!
        return FIRTransactionResult.successWithValue(currentData)
        }) { (error, committed, snapshot) in
            if let error = error {
            print("follow - update following transaction - EXCEPTION: " + error.localizedDescription)
        }
    }
}

This adds the uid of userToFollow to the array Following of user. It can handle nil values and will initialize accordingly, as well as will disregard the request if the user is already following the uid of userToFollow. Let me know if you have any questions!

Some useful links:

  1. The comments of firebase runTransactionBlock
  2. The answer to Upvote/Downvote system within Swift via Firebase
  3. The second link I posted above
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!