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

后端 未结 1 1490
我寻月下人不归
我寻月下人不归 2021-01-01 06:05

I\'m trying to create a basic following algorithm using Swift and Firebase. My current implementation is the following:

static func follow(user: FIRUser, use         


        
相关标签:
1条回答
  • 2021-01-01 06:11

    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
    0 讨论(0)
提交回复
热议问题