Im trying to figure out how to search/Query a PFObject and not a user. This is what I have to so far and its finding but not displaying. I found this post and followed it but did not come to a running result because it does not show results. I cant figure out how to show the PFObject so thats what I need help with:)
-(void)filterResults:(NSString *)searchTerm {
[self.searchResults removeAllObjects];
PFQuery *query = [PFQuery queryWithClassName:#"New"];
[query whereKeyExists:#"by"]; //this is based on whatever query you are trying to accomplish
[query whereKeyExists:#"title"]; //this is based on whatever query you are trying to accomplish
[query whereKey:#"title" containsString:searchTerm];
NSArray *results = [query findObjects];
NSLog(#"%#", results);
// NSLog(#"%u", results.count);
[self.searchResults addObjectsFromArray:results];
}
Then I am trying to display here:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *CellIdentifier = #"Cell";
PFTableViewCell *cell = (PFTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[PFTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [object objectForKey:self.textKey];
if (tableView != self.searchDisplayController.searchResultsTableView) {
/* PFObject *title = [PFQuery queryWithClassName:#"title"];
PFQuery *query = [PFQuery queryWithClassName:#"New"];
PFObject *searchedUser = [query getObjectWithId:title.objectId]; NSString * usernameString = [searchedUser objectForKey:#"title"]; cell.textLabel.text = [NSString stringWithFormat:#"%#", usernameString];
*/
PFQuery *query = [PFQuery queryWithClassName:#"New"];
[query whereKey:#"title" equalTo:#"by"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// The find succeeded.
NSLog(#"Successfully retrieved %d title", objects.count);
// Do something with the found objects
for (PFObject *object in objects) {
NSLog(#"%#", object.objectId);
}
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]) {
PFQuery *query = [PFQuery queryWithClassName:#"New"];
[query whereKey:#"title" equalTo:#"by"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// The find succeeded.
NSLog(#"Successfully retrieved %d title", objects.count);
// Do something with the found objects
for (PFObject *object in objects) {
NSLog(#"%#", object.objectId);
}
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
/* //PFObject *obj2 = [self.searchResults objectAtIndex:indexPath.row];
PFQuery *query = [PFQuery queryWithClassName:#"New"];
PFObject *searchedUser = [query getObjectWithId:obj2.objectId];
NSString *first = [searchedUser objectForKey:#"title"];
NSString *last = [searchedUser objectForKey:#"by"];
cell.textLabel.text = [first substringToIndex:1];
NSString *subscript = last;
// cell.categoryName.text = [searchedUser objectForKey:#"category"];
*/
}
return cell;
}
What your code is doing is that first, in filterResults, you are retrieving all objects that contain the field "by" and the field "title" and where "title" contains searchTerm.
THEN, when you create a cell, you do another query (which you should never do, as it now has a long-lasting operation to do for each and every cell being displayed. Scrolling this view would never work. And besides; you are comparing the title with the string #"by", which I am pretty sure is not your intention.
So, your main problem is in they way you build your query, and your secondary problem is that you're doing this for every cell.
What you need to do is get all the data you want on the first search, and then iterate through those data in an array when displaying.
Something like:
- (void)viewDidLoad {
PFQuery *query = [PFQuery queryWithClassName:#"TestClass"];
query.cachePolicy = kPFCachePolicyNetworkOnly;
query.limit = 50;
[query whereKey:#"city" equalTo:chosenCity];
[query whereKey:#"sex" equalTo:#"female"];
[query findObjectsInBackgroundWithTarget:self selector:#selector(callbackLoadObjectsFromParse:)];
- (void)callbackLoadObjectsFromParse:(NSArray *)result error:(NSError *)error {
if (!error) {
NSLog(#"Successfully fetched %d entries", result.count);
self.allTestObjects = result;
} else {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}
Then, later in cellForRowAtIndexPath you use this array (no more queries) as the datasource for your data:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
PFObject * testObject = [self.allTestObjects objectAtIndex:indexPath.row],
cell.textLabel.text = [testObject objectForKey:#"name"];
return cell;
}
When working with databases, never do lookups in tableviewcells. Prepare your data first, and then present them with top performance.
Related
I am trying to search through a list of users in my Parse database. To do so I have a search bar controller and table view. When a user is searching, it seems like the search results are a letter behind. For example if I search "Be" it will show all the names starting with "B" instead of "Be" and when I search "Ben" it shows all the users starting with "Be".
Here is my textDidChange Method:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
NSString *string = searchText;
string = string.lowercaseString;
if(string.length>0){
PFUser *currentUser = [PFUser currentUser];
PFQuery *query = [PFQuery queryWithClassName:#"_User"];
[query whereKey:#"name_lower" containsString:string];
[query whereKey:#"username" notEqualTo:currentUser.username];
[query orderByAscending:#"name_lower"];
[query setLimit:1000];
[query findObjectsInBackgroundWithBlock:^(NSArray *array,NSError *error){
if(!error){
results = [[NSArray alloc]initWithArray:array];
[_mainTableView reloadData];
}else{
[ProgressHUD showError:#"Error Searching"];
}
}];
}else{
NSLog(#"NO RESULTS");
results = nil;
[_mainTableView reloadData];
}
}
Then in my cellforrow:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"cell"];
PFUser *user = results[indexPath.row];
[user fetchIfNeeded];
cell.textLabel.text = [NSString stringWithFormat:#"%# - #%#",user[#"name"],user[#"username"]];
cell.detailTextLabel.text = user[#"university"];
}
Hey try to put constraints like this:
[query whereKey:#"name_lower" hasPrefix:string];
instead of
[query whereKey:#"name_lower" containsString:string];
After all I would do it this way:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
NSString *string = searchText;
string = string.lowercaseString;
if(string.length>0){
PFQuery *query = [PFUser query];
[query whereKey:#"name_lower" hasPrefix:string];
[query whereKey:#"username" notEqualTo:[[PFUser currentUser] username]];
[query orderByAscending:#"name_lower"];
[query setLimit:1000];
[query findObjectsInBackgroundWithBlock:^(NSArray *array,NSError *error){
if(!error){
results = array;
[_mainTableView reloadData];
} else {
[ProgressHUD showError:#"Error Searching"];
}
}];
} else {
NSLog(#"NO RESULTS");
results = nil;
[_mainTableView reloadData];
}
}
I am using Parse as a backend of my app, and it seems that the profile photo is not displaying properly, shown in the image:
there is a black strip on john_appleseed's photo.
here is my code for saving the profile image:
NSData *profileData = UIImagePNGRepresentation(cell1.profileView.image);
PFFile *profileFile = [PFFile fileWithName:#"profilePhoto" data:profileData];
[profileFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
{
if (!error)
{
if (succeeded)
{
[user setObject:profileFile forKey:#"profilePhoto"];
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
{
if (!error)
{
}
else
{
}
}];
}
}
}];
here is how I retrieve the image:(inside PFQueryTableViewController)
- (PFQuery *)queryForTable
{
//NSLog(#"called");
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString *filter = [defaults objectForKey:#"topicFilter"];
NSLog(#"queryfortable: %#", filter);
PFQuery *query = [PFQuery queryWithClassName:#"Questions"];
[query includeKey:#"user"];
[query whereKey:#"category" equalTo:filter];
[query orderByDescending:#"createdAt"];
return query;
}
- (PFObject *)objectAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == self.objects.count)
{
return nil;//this is for the load more cell.
}
return [self.objects objectAtIndex:indexPath.section];
}
in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
PFUser *user = [object objectForKey:#"user"];
PFImageView *profileImgView = (PFImageView *)[cell viewWithTag:1];
profileImgView.layer.cornerRadius = profileImgView.frame.size.height/2;
profileImgView.layer.masksToBounds = YES;
PFFile *file = user[#"profilePhoto"];
profileImgView.file = file;
[profileImgView loadInBackground];
any ideas? many thanks.
You should be updating user interfaces on the main thread. Since your loading something in the background, you should notify the main thread that it needs to update an object. loadInBackground is downloading the file asynchronously.
Here is an example, that you can alter for your needs, just to illustrate, that updating UI components in the call back has it's benefits; this is based off of Parses own AnyPic:
NSString *requestURL = file.url; // Save copy of url locally (will not change in block)
[file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
//dispatch on main thread
UIImage *image = [UIImage imageWithData:data];
} else {
NSLog(#"Error on fetching file");
}
}];
I have tried following code so far:
PFGeoPoint * myGeoPoint = [PFUser currentUser][#"coordinates"]; // Your geoPoint
PFQuery *query = [PFUser query];
[query includeKey:#"User"];
[query whereKey:#"coordinates" nearGeoPoint:myGeoPoint withinMiles:radiusInMiles];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if(!error){
for (PFUser *object in objects){
users = (NSArray*)[object ObjectForKey:#"User"];
}
[self.tableView reloadData];
}
}
}];
- (PFUser*) objectAtIndexPath:(NSIndexPath*)indexPath {
PFUser *object = [PFUser objectWithClassName: #"User"];
[object setObject:[users objectAtIndex:indexPath.row] forKey:#"User"];
return object;
}
// Use myObjects for numberOfRowsInSection:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section {
return users.count;
}
//Use your custom object for cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath object:(PFUser *)object {
static NSString *simpleTableIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
// Configure the cell using object
UILabel *reviewLabel = (UILabel *)[cell viewWithTag:10];
reviewLabel.text = [object objectForKey:object.username];
PFFile *userImageFile = object[#"profilePic"];
[userImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error) {
if (imageData != nil)
cell.imageView.image = [UIImage imageWithData:imageData];
else cell.imageView.image= [UIImage imageNamed:#"defaultPerson"];
}
}];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
SMChatViewController *chatController = [SMChatViewController alloc];
// [chatController initWithPhoto:image];
[self presentModalViewController:chatController animated:YES];
}
In this code I am retrieving an array of PFUsers as "objects".When I am saving the objects array to users it returns as empty. So can anyone please suggest me something that How can I set the username and profilepic in a tableView?
I guess query is not correct.
Try this:
PFGeoPoint * myGeoPoint = [PFUser currentUser][#"coordinates"]; // Your geoPoint
PFQuery *query = [PFQuery queryWithObject:#"_User"];
NSArray *userList = [NSArray new];
[query whereKey:#"coordinates" nearGeoPoint:myGeoPoint withinMiles:radiusInMiles];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if(!error){
userList = objects;
[self.tableView reloadData];
}
}];
In your code you're asking 'User' objects, then you fetching 'User' field from this objects.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
static NSString *simpleTableIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
PFUser *user = (PFUser*)[users objectAtIndex:indexPath.row];
cell.textLabel.text=user.username;
PFFile *userImageFile = user[#"profilePic"];
[userImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error) {
if (imageData != nil)
cell.imageView.image = [UIImage imageWithData:imageData];
else cell.imageView.image= [UIImage imageNamed:#"defaultPerson.png"];
}
}];
return cell;
}
I'm currently building a photo messaging app where users can send photos to each other. When the photo is taken, you select recipients from a UITableView in a new View Controller.
But every time I select a person from the list and send the photo, it gets the wrong user.objectId. It seems to take the Friendship objectId which is another class named Friendship, when it should take the objectId of the user. Here's how I'm doing it:
#implementation PickRecipientsViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.recipients = [[NSMutableArray alloc] init];
[_selectedImage setImage:_image];
self.tableView.delegate = self;
[self refreshFriends];
}
- (void)refreshFriends {
[__acceptedRequests removeAllObjects];
PFQuery *friendsQuery = [self queryForFriends];
PFQuery *acceptedRequestQuery = [self queryForAcceptedFriendRequests];
PFQuery *friendRequestsQuery = [self queryForRequests];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
// Find friends
NSArray *objects = [friendsQuery findObjects];
for (PFObject * obj in objects) {
[obj[#"user1"] fetchIfNeeded];
[obj[#"user2"] fetchIfNeeded];
}
_friends = [objects mutableCopy];
// Find pending requests
objects = [friendRequestsQuery findObjects];
for (PFObject *obj in objects) {
[obj[#"fromUser"] fetchIfNeeded];
}
__friendRequests = [objects mutableCopy];
// Find accepted requests
objects = [acceptedRequestQuery findObjects];
for (PFObject *obj in objects) {
PFUser *to = (PFUser*)[obj[#"toUser"] fetchIfNeeded];
[obj deleteEventually];
[__acceptedRequests addObject:to[#"username"]];
}
// show accepted requests
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
if (__acceptedRequests.count > 0) {
NSString *friends = __acceptedRequests[0];
for (int i = 1; i < __acceptedRequests.count; ++i) {
friends = [friends stringByAppendingFormat:#", %#", __acceptedRequests[i]];
}
friends = [friends stringByAppendingString:#" accepted your friend request"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"New Friends" message:friends delegate:self cancelButtonTitle:#"Wuhu" otherButtonTitles:nil, nil];
alert.tag = kAlertTagAcceptedRequest;
[alert show];
}
});
});
}
- (PFQuery *)queryForAcceptedFriendRequests {
PFUser *user = [PFUser currentUser];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"status = %# AND (fromUser = %# AND toUser != %#)", #"approved", user, user];
PFQuery *acceptedRequestQuery = [PFQuery queryWithClassName:#"FriendRequest" predicate:predicate];
return acceptedRequestQuery;
}
- (PFQuery *)queryForFriends {
PFUser *user = [PFUser currentUser];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"user1 = %# AND user2 != %# OR user1 != %# AND user2 = %#", user, user, user, user];
PFQuery *friendsQuery = [PFQuery queryWithClassName:#"Friendship" predicate:predicate];
return friendsQuery;
}
- (PFQuery *)queryForRequests {
PFUser *user = [PFUser currentUser];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"status = %# AND (toUser = %# AND fromUser != %#)", #"pending", user, user];
PFQuery *friendRequests = [PFQuery queryWithClassName:#"FriendRequest" predicate:predicate];
return friendRequests;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RecipientsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"RecipientsTableViewCell" forIndexPath:indexPath];
PFUser *user = [self.friends objectAtIndex:indexPath.row];
if([self.recipients containsObject:user.objectId]){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
PFObject *friendRequest = [_friends objectAtIndex:indexPath.row];
PFUser *user1 = (PFUser *)friendRequest[#"user1"];
PFUser *user2 = (PFUser *)friendRequest[#"user2"];
if ([user1.username isEqualToString:[PFUser currentUser].username]) {
cell.nameL.text = user2[#"username"];
[(PFFile*)user2[#"profilePic"] getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (error) {return;}
cell.profilePic.image = [UIImage imageWithData:data];
}];
} else if ([user2.username isEqualToString:[PFUser currentUser].username]) {
cell.nameL.text = user1[#"username"];
[(PFFile*)user1[#"profilePic"] getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (error) {return;}
cell.profilePic.image = [UIImage imageWithData:data];
}];
}
return cell;
}
- (BOOL)isFriend:(PFUser *)user {
for (PFUser *friend in self.friends) {
if ([friend.objectId isEqualToString:user.objectId]) {
return YES;
}
}
return NO;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _friends.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 68;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.tableView deselectRowAtIndexPath:indexPath animated:NO];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
PFUser *user = [self.friends objectAtIndex:indexPath.row];
if (cell.accessoryType == UITableViewCellAccessoryNone){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[self.recipients addObject:user.objectId];
} else{
cell.accessoryType = UITableViewCellAccessoryNone;
[self.recipients removeObject:user.objectId];
}
}
- (IBAction)sendImage {
PFObject *message = [PFObject objectWithClassName:#"Messages"];
[message setObject:[PFUser currentUser] forKey:#"fromUser"];
[message setObject:[PFUser currentUser] forKey:#"toUser"];
[message setObject:#"image" forKey:#"fileType"];
[message setObject:self.recipients forKey:#"recipientIds"];
[message setObject:[[PFUser currentUser] objectId] forKey:#"senderId"];
// Image
NSData *imageData = UIImageJPEGRepresentation(_image, 1.0);
NSString *filename = [NSString stringWithFormat:#"image.png"];
PFFile *imageFile = [PFFile fileWithName:filename data:imageData];
[message setObject:imageFile forKey:#"file"];
[message saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
// Dismiss the controller
[[[self presentingViewController] presentingViewController] dismissViewControllerAnimated:YES completion:nil];
} else {
[SVProgressHUD showErrorWithStatus:#"Oh darn! Something went wrong :("];
}
}];
}
#end
Because _friends is an array of Friendship objects and when a row is tapped you just directly get it out of the array and don't then get the appropriate user from it (like you do when you configure the cell labels).
So in tableView:didSelectRowAtIndexPath: you should have something like:
BOOL adding = NO;
if (cell.accessoryType == UITableViewCellAccessoryNone){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
adding = YES;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
PFObject *friendRequest = [_friends objectAtIndex:indexPath.row];
PFUser *user1 = (PFUser *)friendRequest[#"user1"];
PFUser *user2 = (PFUser *)friendRequest[#"user2"];
PFUser *recipient = nil;
if ([user1.username isEqualToString:[PFUser currentUser].username]) {
recipient = user2;
} else if ([user2.username isEqualToString:[PFUser currentUser].username]) {
recipient = user1;
}
if (adding) {
[self.recipients addObject:recipient.objectId];
} else {
[self.recipients removeObject:recipient.objectId];
}
I'm currently developing a App thats home view controller shows a display of all the users friends, their names and their profile images (if they have one), each within a cell of a UICollectionView. I am using tags to identify the UI elements within each cell and Parse as the backend. Each user and their relations are stored under the class "User" and then their profile images (if they have chosen one/taken one) are stored under another class called "UserImage". I've managed to set their usernames to the cells but having difficulty with the images. Basically each cell is downloading the entire image array, which I believe is causing the app to crash with this error. Also as soon as the user adds a friend without a profile picture the app seems to act strange..
[__NSArrayM objectAtIndex:]: index 8 beyond bounds [0 .. 1]
here is how I save the image to parse.. This is in the users profile view controller.
-(void)uploadImage {
NSData *fileData;
NSString *fileName;
NSString *fileType;
UIImage *newImage = [self scaleImage:self.image toSize:CGSizeMake(340.0,340.0)];
fileData = UIImagePNGRepresentation(newImage);
fileName = #"profileimage.png";
fileType = #"profileimage";
PFFile *file = [PFFile fileWithName:fileName data:fileData];
[file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
PFUser *user = [PFUser currentUser];
PFObject *userImage = [PFObject objectWithClassName:#"UserImage"];
[userImage setObject:file forKey:#"file"];
[userImage setObject:fileType forKey:#"fileType"];
[userImage setObject:user forKey:#"user"];
[userImage saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
NSLog(#"Error saving image");
}
else {
NSLog(#"Image Saved");
}
}];
}];
}
I then query for the current users relations within the viewWillAppear: method of the HomeViewController.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController.navigationBar setHidden:NO];
self.friendsRelation = [[PFUser currentUser] objectForKey:#"friendsRelation"];
self.friends = [[NSMutableArray alloc] init];
PFQuery *query = [self.friendsRelation query];
[query orderByAscending:#"username"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"Error %# %#", error, [error userInfo]);
}
else {
[self.friends addObjectsFromArray:objects];
[self.collectionView reloadData];
}
}];
}
Setting the amount of cells to the amount of the users friends..
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [self.friends count];
}
And finally setting up the cells within the cellForItemAtIndexPath: method
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
PFUser *user = [self.friends objectAtIndex:indexPath.row];
if (cell.tag == 0) {
UILabel *cellLabel = (UILabel *)[cell viewWithTag:25];
cellLabel.text = user.username;
PFImageView *homeImageView = (PFImageView *)[cell viewWithTag:50];
[homeImageView setContentMode:UIViewContentModeScaleAspectFill];
homeImageView.clipsToBounds = YES;
homeImageView.layer.cornerRadius = 7;
self.friendImages = [[NSMutableArray alloc] init];
PFQuery *imageQuery = [PFQuery queryWithClassName:#"UserImage"];
[imageQuery whereKey:#"user" containedIn:self.friends];
[imageQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
//need a statement that defines whether a friend has an image or not, if they do then load that image into their cell, if not then set default image
[self.friendImages addObjectsFromArray:objects];
PFObject *imageObject = [self.friendImages objectAtIndex:indexPath.row];
PFFile *imageFile = [imageObject objectForKey:#"file"];
homeImageView.file = imageFile;
[homeImageView loadInBackground];
NSLog(#"Retrieved %d images", [self.friendImages count]);
}
else {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
return cell;
}
Any help would be appreciated! keep in mind I'm only a couple of weeks into learning iOS..