Firebase值未在标签上更新

时间:2016-11-03 16:14:21

标签: swift firebase firebase-realtime-database

我使用Firebase值创建了一些简单的计算系统。但是,如果我对它进行评级,计算和值都可以,但它不会更新标签。

这就是我获取价值并进行计算的方式:

let ref = FIRDatabase.database().reference().child("Snuses").queryOrdered(byChild: "Brand")
                     .queryEqual(toValue: brandName)
 ref.observeSingleEvent(of: .value, with: { (snapshot) in
      if snapshot.exists(){

           let enumerator = snapshot.children

           while let thisProduct = enumerator.nextObject() as? FIRDataSnapshot {

                  // Chances are you'd have to create a dictionary
                  let thisProductDict = thisProduct.value as! [String:AnyObject]

                  let rating = thisProductDict["rating"] as! Double
                  let ratersCount = thisProductDict["ratersCount"] as! Double

                  let ratingToShow: String = String((ratersCount == 0) ? 0 : rating / ratersCount)

                  let productObject = Product(
                                              rating: rating,
                                              ratersCount: ratersCount, 
                                              ratingToShow: ratingToShow)
                  self.products.append(productObject)
                }

           self.tableView.reloadData()

cellForRowAtIndexPath中,我尝试在标签上显示ratingToShow:

cell.ratingLabel.text = products[indexPath.row].ratingToShow

我添加值的方式如下:

let ratingToShow: String = String((products[indexPath.row].ratersCount == 0) ? 0 : products[indexPath.row].rating / products[indexPath.row].ratersCount)
        cell.likeLabel.text = ratingToShow

            self.databaseRef.child("productRatings").child(self.currentUser.generalDetails.uid).child(self.products[indexPath.row].snusProductTitle).child(self.currentUser.generalDetails.uid).observeSingleEvent(of: .value, with: { (snapshot) in

                if snapshot.value as? Bool == true{


                     self.databaseRef.child("productRatings").child(self.currentUser.generalDetails.uid).child(self.products[indexPath.row].snusProductTitle).child("rating").observeSingleEvent(of: .value, with: { (snapshot) in

                        let currentUserRate = snapshot.value
                        cell.ratingView.rating = currentUserRate as! Double
                    })

                }else{

                    cell.ratingView.rating = 0.0
                }
                cell.ratingView.didFinishTouchingCosmos = { rating in
                if snapshot.value as? Bool == true{

                    self.databaseRef.child("productRatings").child(self.currentUser.generalDetails.uid).child(self.products[indexPath.row].snusProductTitle).child("rating").observeSingleEvent(of: .value, with: { (snapshot) in

                        let currentUserRate = snapshot.value as? Double


                        self.databaseRef.child("Snuses").child(self.products[indexPath.row].snusProductTitle).child("rating").runTransactionBlock({
                            (currentData:FIRMutableData!) in
                            var value = currentData.value as? Double

                            if (value == nil) {
                                value = 0.0
                            }
                            currentData.value = value! - currentUserRate!

                            cell.update(rating)
                            return FIRTransactionResult.success(withValue: currentData)

                        })
                        self.databaseRef.child("Snuses").child(self.products[indexPath.row].snusProductTitle).child("rating").runTransactionBlock({
                            (currentData:FIRMutableData!) in
                            var value = currentData.value as? Double

                            if (value == nil) {
                                value = 0.0
                            }
                            currentData.value = value! + rating

                            cell.update(rating)

                            return FIRTransactionResult.success(withValue: currentData)

                        })
                        self.databaseRef.child("productRatings").child(self.currentUser.generalDetails.uid).child(self.products[indexPath.row].snusProductTitle).runTransactionBlock({
                            (currentData:FIRMutableData!) in
                            var value = currentData.value as? Bool

                            if (value == nil) {
                                value = true
                            }
                            currentData.value = [self.currentUser.generalDetails.uid:true]
                            self.databaseRef.child("productRatings").child(self.currentUser.generalDetails.uid).child(self.products[indexPath.row].snusProductTitle).updateChildValues(["rating": rating])
                            return FIRTransactionResult.success(withValue: currentData)

                        })




                    })

                }else{

                    self.databaseRef.child("Snuses").child(self.products[indexPath.row].snusProductTitle).child("ratersCount").runTransactionBlock({
                        (currentData:FIRMutableData!) in
                        var value = currentData.value as? Double

                        if (value == nil) {
                            value = 0.0
                        }
                        currentData.value = value! + 1
                        return FIRTransactionResult.success(withValue: currentData)

                    })

                    self.databaseRef.child("Snuses").child(self.products[indexPath.row].snusProductTitle).child("rating").runTransactionBlock({
                        (currentData:FIRMutableData!) in
                        var value = currentData.value as? Double

                        if (value == nil) {
                            value = 0.0
                        }
                        currentData.value = value! + rating
                        cell.update(rating)

                        return FIRTransactionResult.success(withValue: currentData)

                    })
                    self.databaseRef.child("productRatings").child(self.currentUser.generalDetails.uid).child(self.products[indexPath.row].snusProductTitle).runTransactionBlock({
                        (currentData:FIRMutableData!) in
                        var value = currentData.value as? Bool

                        if (value == nil) {
                            value = true
                        }
                        currentData.value = [self.currentUser.generalDetails.uid:true]
                        self.databaseRef.child("productRatings").child(self.currentUser.generalDetails.uid).child(self.products[indexPath.row].snusProductTitle).updateChildValues(["rating": rating])
                        return FIRTransactionResult.success(withValue: currentData)

                        })
                    }
                }
                })

我应该采取哪些不同的方式?

1 个答案:

答案 0 :(得分:0)

要轻松操作用户界面中的增量值,一般和最基本的方法是这样的: -

  • 更新Firebase数据库中的帖子:使用 runTransactionBlock

  • 然后将您当前的dataSource更新为Product结构中检索和存储的数据中的相同值。

例如: - 一旦您的用户点击喜欢按钮或喜欢它,您就会在后端(Firebase)和products[indexPath.row].ratingToShow中更新相应操作的值,然后调用 self.tableView.reloadData 即可。这样,每次用户喜欢或不喜欢保存带宽的帖子时,您都不必从数据库中获取当前没有喜欢的内容。

如果你的喜欢按钮在TableViewCell类中有 @IBAction ,那么只需对 yourTableViewController 进行控制器引用并更改数据源: -

class yourTabelViewCell : UITableViewCell{

 var tableController : yourTableViewcontroller!
 var indexPathForCell : Int! 


  @IBAction func likeBtnAction(_ sender: UIButton) {

     //User likes or dislikes the post....

      self.tableController.products[self.indexPathForCell]. ratingToShow = //Manipulate the value +1 or -1
      self.tableController.yourTableView.reloadData()   // Given yourTableView is the custom tableView you have implemented in your viewController
    }
   }

要获取 indexPathForCell ,只需初始化 cellForRowAt indexPath : _

中的值
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "yourTabelViewCell_identifier", for: indexPath) as! yourTabelViewCell

    cell.likeLabel.text = products[indexPath.row].ratingToShow
    cell.indexPathForCell = indexPath.row
    return cell
      }

不要担心用户在喜欢或不喜欢帖子时丢失网络连接, runTransactionBlock 会加载到本地缓存中,因此一旦您的用户重新获得网络连接,那些命令将被执行