2016-09-15 72 views
0

我正在做一個簡單的按鈕。當一個人按下類似按鈕時,代碼正在檢查用戶是否已經按之前的。如果沒有,它會向Firebase發送數據,表示用戶喜歡這篇文章,然後將該按鈕的textColor更改爲藍色。當tableView加載時收到數據

我的問題是,當用戶關閉應用程序並再次打開時,沒有任何按鈕是藍色的。即使用戶喜歡幾個帖子。我需要一些代碼,可以檢查用戶是否已經喜歡該帖子,並且在UITableViewController加載時將textColor更改爲藍色,我猜?

我試圖在我的代碼中這樣做,但它得到一個錯誤。那麼有誰能告訴我如何從這裏出發?我喜歡的按鈕代碼:

func checkClickOnLikeButton() { 
     let dataPathen = self.pathDB 
     // print(dataPathen) 


     if let user = FIRAuth.auth()?.currentUser { 

      let userId = user.uid 



      FIRDatabase.database().reference().child("feed-items").child(dataPathen).child("likesForPost").observeSingleEventOfType(.Value, withBlock: { (snapshot) in 
       // Get user value 
       self.gottenUserId = snapshot.value![userId] as? Bool 

       // print(self.gottenUserId) 

       if self.gottenUserId == true { 
        print("Der er trykket high five før") 
       } else { 
        print("Der er IKKE trykket like før") 
        let quoteString = [userId: true] 
        FIRDatabase.database().reference().child("feed-items").child(dataPathen).child("likesForPost").updateChildValues(quoteString) 
        let blueButtonColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1.0) 
        self.highFiveButton.setTitleColor(blueButtonColor, forState: UIControlState.Normal) 
       } 


       // ... 
      }) { (error) in 
       print(error.localizedDescription) 
      } 



     } 

    } 

回答

0

Id創建一個適合您的數據的結構。然後,我會將您從數據庫中獲取的數據保存在數組中。

在構建表即的cellForRowAtIndexPath,檢查indexPath.row對你的數組中的值,看看你是否喜歡它。 如果你喜歡它,即arrayOfUsers [indexPath.row] .contains(「myUserID」),然後調整你的按鈕顯示已經喜歡,並分配一個數字的計數器。否則,什麼也不做。

另外 - 它不會傷害保持查詢更新,而不是做observeSingleEventOfType(...),我說這是因爲你可以告訴查詢持久性數據,所以即使用戶關閉應用程序。在iPad上啓動您的應用程序,然後返回到手機,iPhone將更新,感謝firebase。

因此,總結一下,我建議將查詢不改爲觀察者一次,並且在兒童被移除/添加時調用特定功能