Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

How do i fetch multiple users from Parse?

Hi, basically i have a collectionView with images in it and each image will be from a different user. I need to somehow query parse for each user's different profile picture to be displayed in each collectionViewCell as well.

Trouble is that fetching users can't be done in CellForItemAtIndexPath as i get an error saying 'NSInvalidArgumentException', reason: 'Can't refresh an object that hasn't been saved to the server.'

My code for fetching the user is:

    self.user = [[PFUser alloc]init];
    self.user.objectId = self.senderName;
    [self.user fetchInBackgroundWithBlock:^(PFObject *object, NSError *error) {
        if (!error){
            NSLog(@"user's username is %@", self.user.username);
            dispatch_async(dispatch_get_main_queue(), ^
                           {

                               [self parsePics];
                               [self refreshCollectionView];

                           });

        }
    }];

and my code for displaying the profile image is:

    if ([picture objectForKey:@"ProfilePic"] == nil){
        [cell.profileImage setImage:[UIImage imageNamed:@"empty_user1"]];
    }
    else{
        [cell.profileImage setFile:[picture objectForKey:@"ProfilePic"]];
    }

How do i get each user's profile picture from Parse ?

Thanks!

2 Answers

Here's the answer for anyone: in viewDidLoad

self.user = [[PFUser alloc]init];

then in viewDidAppear

self.user.objectId = //whatever the objectId is, i was getting it from NSUserDefaults
[self.user fetchInBackground];

Take a look at https://parse.com/docs/ios_guide#queries/iOS. What you're doing above is creating a new PFUser on the device and then asking Parse to go fetch it - but Parse doesn't know about the user because you just created it on the device! What you want to do instead is use a PFQuery - you want to query Parse for a bunch of users to get their information (specifically, their profile pictures). So you should create a new PFQuery and then call something like findObjectsInBackgroundWithBlock to fetch the data. The response you get back will be all the users that apply to your query, so you can then display all of their profile images at once!