Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- I am trying to check if the current user has liked a post uploaded in my application. I am using UICollectionView. The code looks like this:
- var query2 = PFQuery(className: "currentUploads")
- query2.whereKey("objectId", equalTo: post.objID)
- query2.whereKey("likedBy", equalTo: self.thisUser!)
- query2.getFirstObjectInBackgroundWithBlock {
- (object: PFObject?, error: NSError?) -> Void in
- if error != nil || object == nil {
- println("Like does not exist.")
- cell.likeButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
- }
- else{
- println("Like does exist.")
- cell.likeButton.setTitleColor(UIColor.redColor(), forState: .Normal)
- }
- }
- I have been using that code in cellForItemAtIndexPath, and I heard that I should never query in cellForItemAtIndexPath. The "post.objID" is the object id from parse for the current object row. The `"likedBy"` is a array in parse that contains usernames, and "self.thisUser" is the username for the current user.
- Like button action:
- @IBAction func likeButtonAction(sender: AnyObject) {
- let buttonPosition = sender.convertPoint(CGPointZero, toView: self.collectionView)
- let indexPath = self.collectionView.indexPathForItemAtPoint(buttonPosition)
- ////
- //println(indexPath?.item)
- ////
- let post = self.arrayOfDetails[indexPath!.item]
- println(post.likedBy)
- let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! CollectionViewCell
- //cell.likeButton.enabled = false
- if (post.likedBy.containsObject(thisUser!)){
- let queryDislike = PFObject(withoutDataWithClassName: "currentUploads", objectId: post.objID)
- queryDislike.removeObject(self.thisUser!, forKey: "likedBy")
- println("STEP 1: Current user removed from likedBy column")
- //Save
- queryDislike.saveInBackgroundWithBlock {
- (success: Bool, error: NSError?) -> Void in
- if (success) {
- // The object has been incremented
- println("STEP 3: Successfully saved")
- self.queryFromParse()
- } else {
- // There was a problem, check error.description
- //println(error!.description)
- }
- }
- }
- else{
- let queryLike = PFObject(withoutDataWithClassName: "currentUploads", objectId: post.objID)
- queryLike.addObject(self.thisUser!, forKey: "likedBy")
- println("STEP 1: Current user added to likedBy column")
- // Save
- queryLike.saveInBackgroundWithBlock {
- (success: Bool, error: NSError?) -> Void in
- if (success) {
- // The object has been incremented
- println("STEP 3: Successfully saved")
- self.queryFromParse()
- } else {
- // There was a problem, check error.description
- //println(error!.description)
- }
- }
- }
- }
- And suggestions on how I can do this? If the user already has liked a photo, the button will be red, if the user has not liked the photo, the button will be blue(color is for testing only).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement