就像Firebase中的按钮一样 [英] Like button in Firebase swift

查看:144
本文介绍了就像Firebase中的按钮一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为我的UITableViewCell创建一个类似的按钮。到目前为止,我设法做的是每次按钮被点击时用+1来更新喜欢的数量。然而,我只希望用户能够按下按钮一次,如果用户再次点击该按钮,则用户不喜欢该帖子 - 就像Facebook的按钮一样。



如果有任何帮助,我通过Facebook登录到我的应用程序。



我的代码

  @IBAction func likeTapped(sender:AnyObject){
// print(pathDB)
FIRDatabase.database ).reference()。child(feed-items)。child(pathDB).observeSingleEventOfType(.Value,withBlock:{(snapshot)in
//获取用户值
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如果让dealResul_Initial = resul.value as?Int {

resul.value = dealResul_Initial + 1
// or HowSoEver你想更新你的dealResul。
返回FIRTransactionResult.successWithValue(resul)
} else {
return FIRTransactionResult.successWithValue(resul)
}
} ,andCompletionBlock:$(
$ b $ print(error?.localizedDescription)
print(completion)
print(snap)
if!completion {
print(无法更新节点)
} else {
completionBlock()
}
})
}

b $ b



希望你们能帮助我:)

  {
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,
ui d10:true
}
},
}
}

在检索之前,你必须检查用户是否已经喜欢这个帖子,并相应地设置类似按钮的状态: - $ /

检索的字典用法: - $ / $>

  struct feed {

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

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

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

}

在你的tableViewController中: -

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


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

$ b重写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

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

for feedDict {

如果让feedLikesDict = each.1 [feedLikes] as?NSMutableDictionary {

如果feedLikesDict [currentUerID]!= nil {

let temp = feed.init(like: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(如: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(like:nil,feed:each.1 [feedText] as!String,likeTisPost:false,feedNM:each.0)
self。 feedD.insert(temp,atIndex:0)
self.customTableView.reloadData()
$ b}

}
}





$ b 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

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


返回单元
}


$




$你自定义视图单元:




pre> 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!){
$ b $如果sender.selected == false {

FIRDatabase.database() ().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 else 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.cust omTableView.reloadData()

}




$ b code $

另请参阅: - https://stackoverflow.com/a/39458044 / 6297658


I am trying to create a like button for my UITableViewCell. What I have managed to do so far is update the number of likes with +1 everytime the button is clicked. I, however, only want the user to be able to press the button once, and if it is clicked again by the same user, the user is unliking the post - just as the facebook like button.

If it is any help, I am signing in to my app via facebook.

My code:

@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()
                }
        })
    }

Here you have my structure in firebase:

Hope you guys can help me :)

解决方案

If your JSON is something like this:-

{
  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"
                    }   
           },
      }
  }

Before retrieving you will have to check if the user had already liked this post, and set the state of the like button accordingly:-

For storing the retrieved dictionary use:-

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
    }

}

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



}

You 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()

        }


    }

}

Also see :-https://stackoverflow.com/a/39458044/6297658

这篇关于就像Firebase中的按钮一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆