2016-09-14 54 views
2

我想爲我的UITableViewCell創建一個像按鈕。到目前爲止,我設法做的是每次點擊按鈕時用+1來更新喜歡的數量。然而,我只希望用戶能夠按下按鈕一次,如果同一用戶再次點擊該按鈕,則用戶不喜歡該帖子 - 就像Facebook的按鈕一樣。像Firebase中的按鈕swift

如果有任何幫助,我通過Facebook登錄到我的應用程序。

我的代碼:

@IBAction func likeTapped(sender: AnyObject) { 
     //print(pathDB) 
     FIRDatabase.database().reference().child("feed-items").child(pathDB).observeSingleEventOfType(.Value, withBlock: { (snapshot) in 
      // Get user value 
      let antalLikes = snapshot.value!["likesForPost"] as! Int 
      print(antalLikes) 
      let dataPathen = self.pathDB 
      print(dataPathen) 

       self.updateTotalNoOfPost{ 
        print("Updated") 
       } 

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

    func updateTotalNoOfPost(completionBlock : (() -> Void)){ 

     let prntRef = FIRDatabase.database().reference().child("feed-items").child(pathDB).child("likesForPost") 

     prntRef.runTransactionBlock({ (resul) -> FIRTransactionResult in 
      if let dealResul_Initial = resul.value as? Int{ 

       resul.value = dealResul_Initial + 1 
       //Or HowSoEver you want to update your dealResul. 
       return FIRTransactionResult.successWithValue(resul) 
      }else{ 
       return FIRTransactionResult.successWithValue(resul) 
      } 
      }, andCompletionBlock: {(error,completion,snap) in 

       print(error?.localizedDescription) 
       print(completion) 
       print(snap) 
       if !completion { 
        print("Couldn't Update the node") 
       }else{ 
        completionBlock() 
       } 
     }) 
    } 

這裏有我的結構,火力點: enter image description here

希望你們能幫助我:)

+0

嘗試在'prntRef.runTransactionBlock({...',你得到什麼?我的猜測是你會得到它零。你在哪裏聲明'pathDB',你在哪裏初始化它? – Dravidian

+0

pathDB正在初始化,我沒有得到一個零,因爲我打印dataDBathen這是pathDB。代碼沒有問題,我只是要求幫助實現一個像我上面提到的功能的按鈕。你能做到嗎?我想爲你付出時間。 –

回答

3

如果你的JSON是這樣的: -

{ 
    feed-items: { 
    feedItem1 :{ 
      feedText : "This is feed1", 
      feedLikes : {uid1 : "true", 
         uid2 : "true" 
        } 
      }, 
     feedItem2 :{ 
      feedText : "This is feed2", 
      feedLikes : {uid13 : "true", 
         uid2 : "true" 
        } 
      }, 
     feedItem3 :{ 
      feedText : "This is feed4", 
      feedLikes : {uid4 : "true", 
         uid10 : "true" 
        } 
      }, 
     } 
    } 

之前檢索你必須檢查用戶是否已經喜歡這個職位,並相應地設置類似按鈕的狀態: -

對於存儲檢索字典用途: -

struct feed { 

    var feedLikes : NSMutableDictionary! 
    var feedText : String! 
    var doILikeThisPost : Bool! 
    var feedNameI : String! 

    init(likes:NSMutableDictionary!, feed : String!, likeTisPost : Bool!, feedNM : String!){ 

     self.doILikeThisPost = likeTisPost 
     self.feedLikes = likes 
     self.feedText = feed 
     self.feedNameI = feedNM 
    } 

} 

在你tableViewController : -

import UIKit 
import Firebase 
class customTableViewController : UIViewController, UITableViewDelegate ,UITableViewDataSource{ 


var feedD = [feed]() 
@IBOutlet wear var customTableView : UITableView! 


override func viewWillAppear(animated: Bool) { 
    super.viewWillAppear(animated) 
    customTableView.delegate = self 
    customTableView.dataSource = self 
    retrieveTheData() 


} 





func retrieveTheData(){ 

    FIRDatabase.database().reference().child("feed-items").observeSingleEventOfType(.Value, withBlock: {(allFeeds) in 

     if let feedDict = allFeeds.value as? [String: AnyObject]{ 

      for each in feedDict{ 

       if let feedLikesDict = each.1["feedLikes"] as? NSMutableDictionary{ 

        if feedLikesDict[currentUerID] != nil{ 

         let temp = feed.init(likes: feedLikesDict, feed: each.1["feedText"] as! String, likeTisPost: true, feedNM : each.0) 
         self.feedD.insert(temp, atIndex: 0) 
         self.customTableView.reloadData() 
        }else{ 

         let temp = feed.init(likes: feedLikesDict, feed: each.1["feedText"] as! String, likeTisPost: false, feedNM : each.0) 
         self.feedD.insert(temp, atIndex: 0) 
         self.customTableView.reloadData() 
        } 
       }else{ 

        let temp = feed.init(likes: nil, feed: each.1["feedText"] as! String, likeTisPost: false, feedNM : each.0) 
        self.feedD.insert(temp, atIndex: 0) 
        self.customTableView.reloadData() 

       } 

      } 
     } 

    }) 
} 




func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return feedD.count ?? 0 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = self.customTableView.dequeueReusableCellWithIdentifier("CELL") as! customCell 

    if feedD[indexPath.row].doILikeThisPost == true{ 

     cell.feedLikeBtn.selected = true 
     cell.feedTextPost = feedD[indexPath.row].feedText 
     cell.feedName = feedD[indexPath.row].feedNameI 
     cell.parentTableViewController = self 
     cell.indexPathForRow = indexPath.row 
    }else{ 

     cell.feedLikeBtn.selected = false 
     cell.feedTextPost = feedD[indexPath.row].feedText 
     cell.feedName = feedD[indexPath.row].feedNameI 
     cell.parentTableViewController = self 
     cell.indexPathForRow = indexPath.row 
    } 


    return cell 
    } 



} 

您customTableViewCell: -

class customCell : UITableViewCell{ 

@IBOutlet weak var feedLikeBtn : UIButton! 
var feedTextPost = String() 
var feedName = String() 
var indexPathForRow : Int! 


var parentTableViewController : customTableViewController! 

@IBAction func likeBtn(sender:UIButton!){ 

    if sender.selected == false{ 

     FIRDatabase.database().reference().child("feed-items").child(feedName).child("feedLikes").updateChildValues([currentUserID : "true"]) 
     self.parentTableViewController.feedD[self.indexPathForRow].feedLikes.setObject("true", forKey: currentUserID) 
     self.parentTableViewController.feedD[self.indexPathForRow].doILikeThisPost = true 
     self.parentTableViewController.customTableView.reloadData() 


    }else if sender.selected == true{ 

     FIRDatabase.database().reference().child("feed-items").child(feedName).child("feedLikes").child(currentUserID).removeValue() 
     self.parentTableViewController.feedD[self.indexPathForRow].feedLikes.removeObjectForKey(currentUserID) 
     self.parentTableViewController.feedD[self.indexPathForRow].doILikeThisPost = false 
     self.parentTableViewController.customTableView.reloadData() 

     } 


    } 

} 

另請參閱: - https://stackoverflow.com/a/39458044/6297658

+0

讓我知道如果你得到這個工作.. – Dravidian

+0

我不幸的是..我不能讓它與我自己的代碼工作。 –

+0

恐怕這是儘可能多的幫助,因爲你可以在這裏......但是,這個謊言的基本概念是一樣的...... – Dravidian