I am trying to implement a like/unlike feature in my iOS app using Swift 2.0, Storyboard, and Parse where users can like/unlike posts created by other users or themselves - just like Instagram, Facebook, and other social apps.
I have a button wired up in the Storyboard to an IBOutlet
called likeButton
and an IBAction
called likeButtonTapped
.
I am confident that the cellForRowAtIndexPath
method is also involved in implementing this functionality correctly.
I think that I have the right idea of what needs to happen in the comments of my code below, however, I do not know how to check if a specific post is liked or not. How do I check if the post is liked or not so that I can toggle the likeButton
image, increment/decrement the likeCount
, and add/remove the relation between the current user and the post that the user likes.
Also, am I taking the "right" (conventional) approach for a standard like/unlike feature? I would love to hear your feedback. Thank you for your time and help!
class TimelineFeedViewController: PFQueryTableViewController {
var userLike = PFUser.currentUser()?.relationForKey("likes")
@IBAction func likeButtonTapped(sender: UIButton) {
// The following code has errors - for example, `object` is an unresolved
// identifier (it's supposed to be a PFObject that holds a post at a specific
// indexPath)
// Also, I cant access the likeButton for some reason. Only when I do
// cell.likeButton in `cellForRowAtIndexPath`.
// If the button is liked already (it's filled)
// Toggle likeButton image to UNfilled version
// "if likeButton isLiked == true" below is pseudocode of what I am trying to do
if likeButton isLiked == true {
let image = UIImage(named: "likeButtonUnfilled")
cell.likeButton.setImage (image, forState: UIControlState)
// Decrement the likeCount
object!.decrementKey("count")
// Remove the relation bet user and post
self.userLike?.removeObject(object!)
} else {
// the button is NOT liked already (it's not filled)
// toggle the image to the filled version
let image = UIImage(named: "likeButton")
cell.likeButton.setImage (image, forState: UIControlState)
// Increment the likeCount
object!.incrementKey("count")
// Add the relation bet. user and post
self.userLike?.addObject(object!)
}
object!.saveIngBackground()
PFUser.currentUser()?.saveInBackground()
self.tableView.reloadData()
}
}