2016-11-03 2 views
0

Firebase 값으로 간단한 계산 시스템을 만들었습니다. 그러나 그것을 평가하면 계산과 값은 괜찮지 만 레이블을 업데이트하지는 않습니다.라벨에 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) 

         }) 
        } 
       } 
       }) 

어떻게해야합니까?

+0

실행할 수 있도록 runTransactionBlock 년대 로컬 캐시에로드 문제가 셀 텍스트를 채우는 코드에서 더 많이 나타나는 것처럼 문제를 이해하는 데 충분한 정보가 부족합니다. 그러나 제품 오브젝트로 작업하는 경우 cell.likeLabel.text = productObject.ratingToShow와 같을 것입니다. – Jay

+0

제품 구조도 예입니다. –

+0

글쎄, 당신의 질문에 코드는 개념적으로 괜찮지 만, 분명히 productName, snusNicotine 등이 빠져서 ProductObject를 채워서 코드가 작동하지 않을 것입니다. 우리가 셀을 채우는 코드를 살펴볼 필요가 있다고 생각합니다.또한 여기저기서 print 문을 던져 제품 배열의 productObject가 변경되거나 생략되지 않도록 할 수 있습니다. – Jay

답변

0

쉽게 사용자 인터페이스에서 증분 값을 조작하려면 일반적이고 가장 기본적인 방법은 다음과 같은 : - 귀하의 중포 기지 데이터베이스에 글

  • 업데이트 : 사용 runTransactionBlock

  • 그런 다음 Product 구조체의 검색된 데이터와 저장된 데이터에서 동일한 값으로 현재 데이터 소스를 업데이트하십시오.

    예를 들어

: - 사용자가 같은 버튼을 클릭하면 그것을 좋아하거나 싫어, 당신의 업데이트를 백엔드 (중포 기지)에서 각 작업의 값을, 또한 products[indexPath.row].ratingToShow에서 다음 호출 self.tableView.reloadData. 이렇게하면 사용자가 대역폭을 절약하는 게시물을 좋아하거나 싫어할 때마다 데이터베이스의 현재 좋아요 수를 가져올 필요가 없습니다.

당신 같은 버튼은 그럼 그냥 yourTableViewController에 컨트롤러 참조하고 데이터 소스 변경 TableViewCell 클래스의 @IBAction의 경우 : - 단지의 indexPathForCell을 얻기 위해

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 
    } 
    } 

을 귀하의 가치를 초기화하십시오 cellForRowAt indexPath : _

,210

그리고 좋아하거나 게시물을 싫어하는 동안 네트워크 연결을 잃어버린 사용자에 대해 걱정하지 마십시오, 사용자가 네트워크 연결을 회복하면 해당 명령이있다

+0

문제는, 그것을 좋아하지 않아, 그것은 평가입니다. 나는 그것을 계산해야 해. 그래서 나는 화장 적으로 값을 더할 수 없습니다. 좋아하는 시스템은 쉽습니다. –

+0

귀하의 평가가 평균입니까? ratersCount에서 사용자 비율을 계산 한 후에 알고리즘을 함께 넣으면 (사용자가 데이터 소스와 백엔드에서 동시에 사용자가 평가 한 비율로 +1하고 등급을 매기고 UI에서 계산하여 제시하면됩니다) 백엔드에 전화하면 변경 사항이 즉시 반영되며, 유일한 수학, 선호도 및 평점은 잠재적으로 동일하거나 거의 수학적 조작을받지 않습니다. – Dravidian

+0

그 알고리즘이 있습니다. 내 주어진 코드를 보면 그 코드를 볼 수 있습니다. –

관련 문제