swiftparse-platformpfquerypfuser

Swift & Parse - Am trying to retrieve a username with a query.


I am trying to retrieve the username belonging to a post. The username can be found in another class however.

These are the two classes I have: Post User

I am populating all the information from the Posts class in a UICollectionView but since the username is in the User class my query is not working. Here's my code...

 //QUERY LOST

    let querylost = PFQuery(className: "Post")
    querylost.order(byDescending: "createdAt")
    querylost.whereKey("lostfound", equalTo: "lost")
    querylost.findObjectsInBackground { (objects, error) in

        if let posts = objects {

            for post in posts {


                self.addresslost.append(post["address"] as! String)

                self.breedlost.append(post["breed"] as! String)

                self.phonelost.append(post["phone"] as! String)

                self.imageFileslost.append(post["imageFile"] as! PFFile)

                //HERE'S THE PROBLEM - username is in User Class

                self.usernames.append(self.queryusers[post["userid"] as! String]!)

                //ENDS here

                self.lostCollectionView.reloadData()

                self.refresherLost.endRefreshing()


            }
        }
    }

    //TO SHOW DATA

    scrollView.delegate = self
    lostCollectionView.delegate = self
    lostCollectionView.dataSource = self

}

Solution

  • Instead of using the userid field, you should create a pointer to put on your Post object instead. Then you can access the User object via the Post object.

    Your code would look something like this:

    let querylost = PFQuery(className: "Post")
    querylost.order(byDescending: "createdAt")
    querylost.include("user")
    querylost.whereKey("lostfound", equalTo: "lost")
    querylost.findObjectsInBackground { (objects, error) in
    
        if let posts = objects {
    
            for post in posts {
    
    
                self.addresslost.append(post["address"] as! String)
    
                self.breedlost.append(post["breed"] as! String)
    
                self.phonelost.append(post["phone"] as! String)
    
                self.imageFileslost.append(post["imageFile"] as! PFFile)
    
                //unwrap the user pointer, and get the username
                if let user = post["user"] as? PFUser, let username = user.username{
                    self.usernames.append(username) 
                }
    
                //ENDS here
    
                self.lostCollectionView.reloadData()
    
                self.refresherLost.endRefreshing()
    
    
            }
        }
    }