qwerty567111 qwerty567111 - 7 months ago 11
Swift Question

Struggling to append arrays across Parse classes

Hi guys I'm trying to build a simple swipe app to like and dislike uploaded photos. I'm struggling with adding the likes/dislikes to Parse the way that I want them to. I've tried two ways so far:


  • adding the objectId of the posted image to the User who liked/disliked it but the problem is only one of the objectId's shows up in the array.

  • staying in the Parse class where the images are posted to (Post), add the userID of the liker/disliker to the image. This doesn't happen at all, new rows are created with new objectId's everytime an image is liked/disliked.



Ideally I want the users who have liked/disliked the photo in a single array so I can query this later. I don't have a great understanding of Parse, it's my first time using it so any help will be massively appreciated.

Here is the code I'm using when an image is swiped (adding to Post class):

if gesture.state == UIGestureRecognizerState.Ended {

var likedOrDisliked = ""

if label.center.x < 100 {

print("Dislike")
likedOrDisliked = "disliked"

} else if label.center.x > self.view.bounds.width - 100 {

print("Like")
likedOrDisliked = "liked"

}

if likedOrDisliked != ""{

var post = PFObject(className: "Post")

post.addUniqueObjectsFromArray([(PFUser.currentUser()?.objectId!)!], forKey: likedOrDisliked)
post.saveInBackground()


}


This is the snippet of when I try adding to User class:

PFUser.currentUser()?.addUniqueObjectsFromArray([displayedUserID], forKey: likedOrDisliked)
do {

try PFUser.currentUser()?.save()

} catch {

}


Here is what happens in the dashboard,
new rows created

Answer

I've tried a lot of things and eventually something stuck, the desired effect was achieved through (added the current user to the liked or disliked fields) :

            if likedOrDisliked != ""{

            var post = PFQuery(className: "Post")


            post.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in

                if error == nil {
                    if let objects = objects {
                        for object in objects {
                            var objId = object["objectId"]
                            var query = PFQuery(className: "Post")

                            query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

                                if error == nil {

                                    object.addUniqueObjectsFromArray([(PFUser.currentUser()?.objectId)!], forKey: likedOrDisliked)

                                    object.saveInBackground()

                                }

                            })
                        }
                    }
                }

            })