如何在Firebase数据库(Swift)中增加子值?

时间:2019-01-14 06:00:09

标签: swift firebase-realtime-database increment

每次用户单击按钮时,我都想通过添加例如来更新用户的积分,获胜和损失。完成任务后刚收到的积分。但是,我不确定该怎么做。我会使用update,在另一个函数中检索子代并将其添加到其中,还是其他?我下面的函数将数据写入Firebase以完成任务,但不会增加子值(相反,它将替换我不需要的值)。

static func create(username: String, posValue: Int, negValue: Int, wins: Int, losses: Int) {

    let rootRef = Database.database().reference()

    let totalPoints = posValue - negValue

    let profileRef = Database.database().reference().child("profile").child(username).childByAutoId()
    _ = profileRef.key

    var multiUpdateValue = [String: Any]()

    let profileDict: [String: Any] = ["totalPoints":  totalPoints,
                                       "posPoints":  posValue,
                                       "negPoints": negValue,
                                       "wins": wins,
                                       "losses": losses]


    multiUpdateValue["profile/\(username)/\(profileRef.key ?? "")"] = profileDict

    rootRef.updateChildValues(multiUpdateValue) { error, ref in
        if let error = error {
            assertionFailure(error.localizedDescription)
            return
        }
    }
}

我想知道是否可以向profileDict添加一些内容。例如,对于“ totalPoints”子级,我可以将其设置为firebase中的totalPoints和已经存在的totalPoints。

    let profileDict: [String: Any] = ["totalPoints":  totalPoints + (something???),
                                       "posPoints":  posValue + (something???),
                                       "negPoints": negValue + (something???),
                                       "wins": wins + (something???),
                                       "losses": losses + (something???]

0 个答案:

没有答案