'NSInvalidArgumentException',原因:“ JSON写操作中的数字值无效(无穷大)”

时间:2019-05-01 03:53:47

标签: json swift firebase-realtime-database

我想做的是:让用户对商店进行评分,然后更新Firebase中的storeRate值。

enter image description here

单击POST后,出现错误:

  

'NSInvalidArgumentException',原因:“ JSON写入中的数字值无效(无限)”

//Initialize Variables
var storeRateIni = 0.0
var reviewCount = 0.0
var receivedId = 1             //receive storeId from parent View Controller

refStore = Database.database().reference().child("stores")
refUpdate = Database.database().reference().child("stores").child(String(receivedId))

refStore.observe(DataEventType.value, with: {(snapshot) in
    if snapshot.childrenCount > 0{
        for store in snapshot.children.allObjects as! [DataSnapshot]{
            let storeObject = store.value as? [String: AnyObject]
            let storeId = storeObject?["storeId"] as! Int
            if (storeId == self.receivedId) {
                //Get value store in Firebase
                let storeRate = storeObject?["storeRate"] as! Double
                let storeReviewCount = storeObject?["storeReviewsCount"] as! Double
                //Do the calculation
                let storeRateUpdate = (storeRate + self.userRate.rating) / storeReviewCount
                //Update to Firebase
                self.reviewCount = storeReviewCount + 1
                self.storeRateIni = storeRateUpdate
                self.refUpdate.updateChildValues(["storeRate": self.storeRateIni])                     
                self.refUpdate.updateChildValues(["storeReviewsCount": self.reviewCount])                         
}}}})

1 个答案:

答案 0 :(得分:0)

此行

let storeRateUpdate = (storeRate + self.userRate.rating) / storeReviewCount

Double.inifinity时生成storeReviewCount == 0.0,这在JSON中无法表示。

您可能需要与其他案件分开处理案件storeReviewCount == 0.0

例如:

let storeRateUpdate = storeReviewCount == 0.0
    ? 0.0
    : (storeRate + self.userRate.rating) / storeReviewCount