【问题标题】:Retrieve an amount value from firebase make a subtraction and update amount using swift 3从firebase检索金额值使用swift 3进行减法和更新金额
【发布时间】:2017-08-24 14:44:30
【问题描述】:

我正在使用 swift 3 和 firebase 构建一个应用程序,我想从数据库中检索一个金额进行减法,然后再次更新 firebase 上的金额。我的 firebase 数据结构具有如下所示的功能。

功能:

func updateBal(cred: String){
    //creating artist with the new given values

    if ( cred != "" ) {
        let credit = ["credits": cred]
        let newCredit = credit as! Int
        let bal = newCredit - 1

        //let newBalanceString: [AnyHashable: Any] = [:]
        //let newBalanceString: [AnyHashable: Any] = [AnyHashable(bal): "/(bal)"]

        let newBalanceString = String(format:"%.2f", bal)
        ref.child("users").child(self.user.uid).child("creditdetails").childByAutoId().updateChildValues(newBalanceString)

        //displaying message
        //LabelMessage.text = "Balance Updated!"
    }
}

数据结构

当我取消注释 [AnyHashable: Any] 行时,应用程序在此行崩溃:

let newCredit = credit as! Int

但是当我用[AnyHashable: Any] 注释掉该行时,我在该行得到一个错误:

ref.child("users").child(self.user.uid).child("creditdetails").childByAutoId().updateChildValues(newBalanceString)

错误提示:

无法将 String 类型的值转换为预期的参数类型 [AnyHashable: Any]

您能否指出我如何解决这个问题的正确方向?

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    let newCredit = credit as! Int 行应该总是给你一个错误。您不能将 Dictionary 类型转换为 Int 类型。要将积分作为 Int 检索,您可以这样做:

    if let newCredit = Int(cred) {
        let bal = newCredit - 1
    }
    

    由于您的 cred 值是作为 Int 检索的,因此无需指定类型 %.2f 此外,您可以直接创建您的字典,如下所示(使用“credits”字符串作为键,因为它始终是这个值):

    if let newCredit = Int(cred) {
        let bal = newCredit - 1
    
        let newBalanceString = ["credits" : bal]
        ref.child("users").child(self.user.uid).child("creditdetails").childByAutoId().updateChildValues(newBalanceString)
    }
    

    【讨论】:

    • 嗨,Damien,我确实喜欢你的建议,但仍然没有在 firebase 上扣除。我似乎无法让它工作。是否有其他解决方法可以使其正常工作
    • 如果您不再有错误,那就是一个开始。现在您在 Firebase 上看不到任何更新?查看您的 Firebase 规则(自动化),检查您从应用发送的具体内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 2022-06-13
    • 1970-01-01
    • 2011-11-03
    • 2017-07-28
    • 1970-01-01
    • 2012-09-16
    相关资源
    最近更新 更多