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];
}
Related
I know that the cellForRowAtIndexPath method isn't being called because I never see the NSLog messages inside of it. I have set the dataSource and delegate attributes of the UITableView and I also have declared UITableViewDelegate and UITableViewDataSource in the header file. What am I missing?
- (void)viewDidLoad {
[self.view setBackgroundColor:[UIColor grayColor]];
tableData = [[NSMutableArray alloc] init];
matchesForUser = [[NSMutableArray alloc] init];
sortedFirstArray = [[NSArray alloc] init];
sortedSecondArray = [[NSArray alloc] init];
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20) style:UITableViewStylePlain];
_tableView.dataSource = self;
_tableView.delegate = self;
[self.view addSubview:_tableView];
countUsers = 0;
PFQuery *query = [PFQuery queryWithClassName:#"_User"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
for (PFObject *object in objects) {
NSLog(#"%#", object.objectId);
tableData[countUsers] = [object valueForKey:#"username"];
matchesForUser[countUsers] = [object valueForKey:#"matches"];
}
}else{
NSLog([error description]);
}
NSLog(#"***tabledata***");
NSLog([NSString stringWithFormat:#"%lu", (unsigned long)[tableData count]]);
NSLog(#"***matchesdata***");
NSLog([NSString stringWithFormat:#"%lu", (unsigned long)[matchesForUser count]]);
}];
dictionary = [NSDictionary dictionaryWithObjects:matchesForUser forKeys:tableData];
sortedFirstArray = [[dictionary allKeys] sortedArrayUsingSelector:#selector(compare:)];
sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
backToMap = [[UIButton alloc] initWithFrame:CGRectMake(80, 518, 160, 30)];
backToMap.backgroundColor = [UIColor colorWithRed:33.0f/255.0f green:156.0f/255.0f blue:41.0f/255.0f alpha:1.0f];
[backToMap addTarget:self action:#selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
[backToMap setTitle:#"BACK TO MAP" forState:UIControlStateNormal];
[self.view addSubview:backToMap];
}
- (void)dismiss {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSString *username = [[sortedFirstArray objectAtIndex:indexPath.row] stringByAppendingString:#" "];
NSString *matchAmount = [sortedSecondArray objectAtIndex:indexPath.row];
NSLog(#"***username***");
NSLog(username);
NSLog(#"***matchamount***");
NSLog(matchAmount);
cell.textLabel.text = [username stringByAppendingString:matchAmount];
return cell;
}
Try doing the following things
1.) Register your tableView like
[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"SimpleTableItem"];
2.) Then Add [_tableView reloadData]; just below
for (PFObject *object in objects) {
NSLog(#"%#", object.objectId);
tableData[countUsers] = [object valueForKey:#"username"];
matchesForUser[countUsers] = [object valueForKey:#"matches"];
}
Inside if (!error) part..
So your Updated Code must look like
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
for (PFObject *object in objects) {
NSLog(#"%#", object.objectId);
tableData[countUsers] = [object valueForKey:#"username"];
matchesForUser[countUsers] = [object valueForKey:#"matches"];
}
[_tableView reloadData];
}else{
NSLog([error description]);
}
NSLog(#"***tabledata***");
NSLog([NSString stringWithFormat:#"%lu", (unsigned long)[tableData count]]);
NSLog(#"***matchesdata***");
NSLog([NSString stringWithFormat:#"%lu", (unsigned long)[matchesForUser count]]);
}];
1) Here you do need to use countUsers = 0;If you need than you need to increment the value inside for loop by 1.Otherwise it will overwrite the value at index 0 every time.
2) You are using background calling method to fetch data.So it will take time to fetch data and control will go further and execute following code.But At that time matchesForUser array is empty, and dictionary is also empty.So in cell it won't display anything and you will not see NSLOG from cell.
Instead of this
ini
dictionary = [NSDictionary dictionaryWithObjects:matchesForUser forKeys:tableData];
sortedFirstArray = [[dictionary allKeys] sortedArrayUsingSelector:#selector(compare:)];
sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
3) Try with this,
PFQuery *query = [PFQuery queryWithClassName:#"_User"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (!error) {
for (PFObject *object in objects) {
NSLog(#"%#", object.objectId);
[tableData addObject:[object valueForKey:#"username"]];
[matchesForUser addObject:[object valueForKey:#"matches"]];
}
dictionary = [NSDictionary dictionaryWithObjects:matchesForUser forKeys:tableData];
sortedFirstArray = [[dictionary allKeys] sortedArrayUsingSelector:#selector(compare:)];
sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
[_tableView reloadData];
}else{
NSLog([error description]);
}
NSLog(#"***tabledata***");
NSLog([NSString stringWithFormat:#"%lu", (unsigned long)[tableData count]]);
NSLog(#"***matchesdata***");
NSLog([NSString stringWithFormat:#"%lu", (unsigned long)[matchesForUser count]]);
});
}];
Did you reload the Tableview in ViewDidLoad? like
[_tableView reloadData];
Reload the table again after
dictionary = [NSDictionary dictionaryWithObjects:matchesForUser forKeys:tableData];
sortedFirstArray = [[dictionary allKeys] sortedArrayUsingSelector:#selector(compare:)];
sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
[_tableView reloadData];
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableData count];
}
The count is 0? you can type NSLog("%#", #(tableData.count)); or just return 1; for test.
UITableView send the tableView:numberOfRowsInSection: first, if the method return 0. it will not call the cellForRowAtIndexPath.
And as #PiyushSharma mentioned, you should Register your tableView.
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 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..
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.
I am using Parse.com for retrieving my data.I want to retrieve my images from parse via pf query but my approach does not working.I get nothing where my UIImageView is. Here is my code:
PFQuery *query = [PFQuery queryWithClassName:#"Class"];
[query whereKey:#"Yes or No" equalTo:[NSNumber numberWithBool:YES]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// The find succeeded.
NSLog(#"Successfully retrieved %d scores.", objects.count);
for (int i = 0; i < objects.count; i++) {
object = [objects objectAtIndex:i];
NSString *Property1 = [object objectForKey:#"Property1"];
__block UIImage *MyPicture = [[UIImage alloc]init];
PFFile *imageFile = [object objectForKey:#"Resimler"];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error){
if (!error) {
MyPicture = [UIImage imageWithData:data];
}
}];
aClass *AC = [[aClass alloc]initWithProperty:Propert1 Picture:MyPicture];
[self.MyArray addObject:AC];
}
}
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
MyViewViewCell *cell = (MyViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
aClass *mC = [self.MyArray objectAtIndex:indexPath.row];
cell.Label.text = mC.Property;
cell.myImage.image = mC.Picture;
return cell;
}
Edit:
At aClass.h
#interface aClass : NSObject
#property(strong)NSString *Property;
#property(strong)UIImage *Resim;
-(id)initWithProperty:(NSString *)aProperty Picture:(UIImage *)aPicture ;
#end
at aClass.m
#implementation Mekan
#synthesize Property, Picture;
-(id)initWithMekanIsmi:(NSString *)aProperty Picture:(UIImage *)aPicture{
self=[super init];
if(self){
self.Property = aProperty;
self.Picture = aPicture;
}
return self;
}
#end
I know it is kind of a mass code but i have to write those codes to illustrate where i assign myImage. So you can ask where you do not understand
I do it like this:
UIImageView *imageView = [[UIImageView alloc] initWithImage:#"default.png"];
[userIcon getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
imageView.image = [[UIImage alloc] initWithData:data];
} progressBlock:^(int percentDone) {
// update progress
}];
You seem to be assigning it to a UIImage properly, but never setting that image as the image for a UIImageView.