I have been stuck on this all day and I'm looking for some help. I am making an app where someone can type in a web address that web address will be stored in a table view. When the user taps on that cell it will take them to the web view where they can view that site. I am using parse as my backend to store the user input. ( I am not using PFQueryTableView)
Here is my code for the tableViewController:
interface MenuTableViewController : UITableViewController
#property(strong, nonatomic) NSMutableArray *referralArray;
#property (strong, nonatomic) PFObject *selectLink;
#property (nonatomic, strong) NSArray *webInput;
#property (nonatomic, strong) UIRefreshControl *refreshControl;
#end
#interface MenuTableViewController ()
#end
#implementation MenuTableViewController
#synthesize referralArray;
- (void)viewDidLoad
{
[super viewDidLoad];
PFUser *currentUser = [PFUser currentUser];
if (currentUser) {
NSLog(#"Current user: %#", currentUser.username);
}
else {
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
//refresh inbox
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self action:#selector(retrieveMessages) forControlEvents:UIControlEventValueChanged];
//swipe to delete
self.tableView.allowsMultipleSelectionDuringEditing = NO;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController.navigationBar setHidden:NO];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.webInput count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"refCell"forIndexPath:indexPath];
PFObject *web = [self.webInput objectAtIndex:indexPath.row];
cell.textLabel.text = [web objectForKey:#"RefLink"];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.selectLink = [self.webInput objectAtIndex:indexPath.row];
//NSString *fileType = [self.selectLink objectForKey:#"RefLink"];
//[self performSegueWithIdentifier:#"webSegue" sender:self];
NSDictionary *dict = [self.webInput objectAtIndex:indexPath.section];
NSString *link=[dict valueForKey:#"link"];
//Create a URL object.
NSURL *url = [NSURL URLWithString:link];
UINavigationController *nav = [self.storyboard instantiateViewControllerWithIdentifier:#"WebView"];
WebViewController *web = (WebViewController *)nav.topViewController;
web.webLink =url;
}
//swipe to delete
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//try this
PFObject *object = [self.webInput objectAtIndex:indexPath.row];
[object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
[self refreshControl];
[self.tableView reloadData];
}];
}
}
#pragma mark - Helper methods
- (void)retrieveMessages {
PFQuery *query = [PFQuery queryWithClassName:#"Referrals"];
//[query whereKey:#"recipientIds" equalTo:[[PFUser currentUser] objectId]];
//run the query here for messages
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
else {
// We found messages!
self.webInput = objects;
[self.tableView reloadData];
NSLog(#"Retrieved %lu messages", (unsigned long)[self.webInput count]);
}
if ([self.refreshControl isRefreshing]) {
[self.refreshControl endRefreshing];
}
}];
}
#pragma mark - LogOut
- (IBAction)logout:(id)sender {
[PFUser logOut];
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showLogin"]) {
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
}
else if ([segue.identifier isEqualToString:#"webSegue"]) {
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
WebViewController *webView = (WebViewController *)segue.destinationViewController;
webView.webAddress = self.selectLink;
}
}
#end
If Someone could help me out I would greatly appreciate it!
Related
I am trying to add a search bar to my existing table view...
I have added my searchBar property to my .m file and I have added the searchbar delegate and yet I have no avail. I am new to adding search functions to my code.
here is my header
#import
#import "SelectSingleView.h"
#import "SelectMultipleView.h"
#import "AddressBookView.h"
#import "FacebookFriendsView.h"
//-------------------------------------------------------------------------------------------------------------------------------------------------
#interface PeopleView : UITableViewController <SelectSingleDelegate, SelectMultipleDelegate, AddressBookDelegate, FacebookFriendsDelegate>
//-------------------------------------------------------------------------------------------------------------------------------------------------
#property (nonatomic, assign) IBOutlet id<PeopleView>delegate;
#end
and here is the .m file
#import <Parse/Parse.h>
#import "ProgressHUD.h"
#import "utilities.h"
#import "PeopleView.h"
#import "ProfileView.h"
#import "SelectSingleView.h"
#import "SelectMultipleView.h"
#import "AddressBookView.h"
#import "FacebookFriendsView.h"
#import "NavigationController.h"
//-------------------------------------------------------------------------------------------------------------------------------------------------
#interface PeopleView()
{
BOOL skipLoading;
NSMutableArray *users;
NSMutableArray *userIds;
NSMutableArray *sections;
}
#property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
#end
//-------------------------------------------------------------------------------------------------------------------------------------------------
#implementation PeopleView
//#synthesize delegate;
#synthesize searchBar;
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
{
[self.tabBarItem setImage:[UIImage imageNamed:#"tab_people"]];
self.tabBarItem.title = #"People";
//-----------------------------------------------------------------------------------------------------------------------------------------
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(actionCleanup) name:NOTIFICATION_USER_LOGGED_OUT object:nil];
}
return self;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)viewDidLoad
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[super viewDidLoad];
self.title = #"Friends";
self.navigationController.navigationBar.tintColor= [UIColor colorWithRed:(255/256.0) green:(128/256.0) blue:(0/256.0) alpha:(1.0)];
//---------------------------------------------------------------------------------------------------------------------------------------------
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self
action:#selector(actionAdd)];
//---------------------------------------------------------------------------------------------------------------------------------------------
self.tableView.tableFooterView = [[UIView alloc] init];
//---------------------------------------------------------------------------------------------------------------------------------------------
users = [[NSMutableArray alloc] init];
userIds = [[NSMutableArray alloc] init];
// UIButton *facebookButton = [UIButton buttonWithType:UIButtonTypeSystem];
//[facebookButton setBackgroundImage:[[UIImage imageNamed:#"gibrlogo.png"];
//[facebookButton setTitle:#"Facebook Friends" forState:UIControlStateNormal];
// [facebookButton sizeToFit];
//facebookButton.center = CGPointMake(210.0, 30.0);// for center;
// Add an action in current code file (i.e. target)
//[facebookButton addTarget:self action:#selector(facebookButtonPressed:)
// forControlEvents:UIControlEventTouchUpInside];
//[self.view addSubview:facebookButton];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)viewDidAppear:(BOOL)animated
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[super viewDidAppear:animated];
//---------------------------------------------------------------------------------------------------------------------------------------------
if ([PFUser currentUser] != nil)
{
if (skipLoading) skipLoading = NO; else [self loadPeople];
}
else LoginUser(self);
}
#pragma mark - Backend methods
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)facebookButtonPressed:(UIButton *)facebookButton
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
skipLoading = YES;
FacebookFriendsView *facebookFriendsView = [[FacebookFriendsView alloc] init];
facebookFriendsView.delegate = self;
NavigationController *navController = [[NavigationController alloc] initWithRootViewController:facebookFriendsView];
[self presentViewController:navController animated:YES completion:nil];
NSLog(#"facebookButton Pressed");
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)loadPeople
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
PFQuery *query = [PFQuery queryWithClassName:PF_PEOPLE_CLASS_NAME];
[query whereKey:PF_PEOPLE_USER1 equalTo:[PFUser currentUser]];
[query includeKey:PF_PEOPLE_USER2];
[query setLimit:1000];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
{
if (error == nil)
{
[users removeAllObjects];
[userIds removeAllObjects];
for (PFObject *people in objects)
{
PFUser *user = people[PF_PEOPLE_USER2];
[users addObject:user];
[userIds addObject:user.objectId];
}
[self setObjects:users];
[self.tableView reloadData];
}
else [ProgressHUD showError:#"Network error."];
}];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchUsers:(NSString *)search_lower
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
PFQuery *query1 = [PFQuery queryWithClassName:PF_BLOCKED_CLASS_NAME];
[query1 whereKey:PF_BLOCKED_USER1 equalTo:[PFUser currentUser]];
PFQuery *query2 = [PFQuery queryWithClassName:PF_USER_CLASS_NAME];
[query2 whereKey:PF_USER_OBJECTID notEqualTo:[PFUser currentId]];
[query2 whereKey:PF_USER_OBJECTID doesNotMatchKey:PF_BLOCKED_USERID2 inQuery:query1];
[query2 whereKey:PF_USER_FULLNAME_LOWER containsString:search_lower];
[query2 orderByAscending:PF_USER_FULLNAME_LOWER];
[query2 setLimit:1000];
[query2 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
{
if (error == nil)
{
[users removeAllObjects];
[users addObjectsFromArray:objects];
[self.tableView reloadData];
}
else [ProgressHUD showError:#"Network error."];
}];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)setObjects:(NSArray *)objects
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
if (sections != nil) [sections removeAllObjects];
//---------------------------------------------------------------------------------------------------------------------------------------------
NSInteger sectionTitlesCount = [[[UILocalizedIndexedCollation currentCollation] sectionTitles] count];
sections = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
//---------------------------------------------------------------------------------------------------------------------------------------------
for (NSUInteger i=0; i<sectionTitlesCount; i++)
{
[sections addObject:[NSMutableArray array]];
}
//---------------------------------------------------------------------------------------------------------------------------------------------
NSArray *sorted = [objects sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
PFUser *user1 = (PFUser *)obj1;
PFUser *user2 = (PFUser *)obj2;
return [user1[PF_USER_FULLNAME] compare:user2[PF_USER_FULLNAME]];
}];
//---------------------------------------------------------------------------------------------------------------------------------------------
for (PFUser *object in sorted)
{
NSInteger section = [[UILocalizedIndexedCollation currentCollation] sectionForObject:object collationStringSelector:#selector(fullname)];
[sections[section] addObject:object];
}
}
#pragma mark - User actions
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionCleanup
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[users removeAllObjects];
[userIds removeAllObjects];
[sections removeAllObjects];
[self.tableView reloadData];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionAdd
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:#"Search for a Friend" style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) { [self actionSelectSingle]; }];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:#"Add Friends" style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) { [self actionSelectMultiple]; }];
UIAlertAction *action3 = [UIAlertAction actionWithTitle:#"Invite Friends SMS" style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) { [self actionAddressBook]; }];
UIAlertAction *action4 = [UIAlertAction actionWithTitle:#"Invite Facebook Friends" style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) { [self actionFacebookFriends]; }];
UIAlertAction *action5 = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:action1]; [alert addAction:action2]; [alert addAction:action3]; [alert addAction:action4]; [alert addAction:action5];
[self presentViewController:alert animated:YES completion:nil];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionSelectSingle
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
skipLoading = YES;
SelectSingleView *selectSingleView = [[SelectSingleView alloc] init];
selectSingleView.delegate = self;
NavigationController *navController = [[NavigationController alloc] initWithRootViewController:selectSingleView];
[self presentViewController:navController animated:YES completion:nil];
}
#pragma mark - SelectSingleDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)didSelectSingleUser:(PFUser *)user
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[self addUser:user];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionSelectMultiple
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
skipLoading = YES;
SelectMultipleView *selectMultipleView = [[SelectMultipleView alloc] init];
selectMultipleView.delegate = self;
NavigationController *navController = [[NavigationController alloc] initWithRootViewController:selectMultipleView];
[self presentViewController:navController animated:YES completion:nil];
}
#pragma mark - SelectMultipleDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)didSelectMultipleUsers:(NSMutableArray *)users_
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
for (PFUser *user in users_)
{
[self addUser:user];
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionAddressBook
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
skipLoading = YES;
AddressBookView *addressBookView = [[AddressBookView alloc] init];
addressBookView.delegate = self;
NavigationController *navController = [[NavigationController alloc] initWithRootViewController:addressBookView];
[self presentViewController:navController animated:YES completion:nil];
}
#pragma mark - AddressBookDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)didSelectAddressBookUser:(PFUser *)user
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[self addUser:user];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionFacebookFriends
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
skipLoading = YES;
FacebookFriendsView *facebookFriendsView = [[FacebookFriendsView alloc] init];
facebookFriendsView.delegate = self;
NavigationController *navController = [[NavigationController alloc] initWithRootViewController:facebookFriendsView];
[self presentViewController:navController animated:YES completion:nil];
}
#pragma mark - FacebookFriendsDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)didSelectFacebookUser:(PFUser *)user
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[self addUser:user];
}
#pragma mark - Helper methods
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)addUser:(PFUser *)user
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
if ([userIds containsObject:user.objectId] == NO)
{
PeopleSave([PFUser currentUser], user);
[users addObject:user];
[userIds addObject:user.objectId];
[self setObjects:users];
[self.tableView reloadData];
}
}
#pragma mark - Table view data source
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
return [sections count];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
return [sections[section] count];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
if ([sections[section] count] != 0)
{
return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section];
}
else return nil;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"cell"];
NSMutableArray *userstemp = sections[indexPath.section];
PFUser *user = userstemp[indexPath.row];
cell.textLabel.text = user[PF_USER_FULLNAME];
cell.detailTextLabel.text = user[PF_USER_EMAIL];
if(cell.detailTextLabel.text == nil){
cell.detailTextLabel.text = #"Facebook Account";
}
return cell;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
return YES;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
NSMutableArray *userstemp = sections[indexPath.section];
PFUser *user = userstemp[indexPath.row];
//---------------------------------------------------------------------------------------------------------------------------------------------
PeopleDelete([PFUser currentUser], user);
//---------------------------------------------------------------------------------------------------------------------------------------------
[users removeObject:user];
[userIds removeObject:user.objectId];
[self setObjects:users];
//---------------------------------------------------------------------------------------------------------------------------------------------
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
#pragma mark - Table view delegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//---------------------------------------------------------------------------------------------------------------------------------------------
NSMutableArray *userstemp = sections[indexPath.section];
PFUser *user = userstemp[indexPath.row];
//---------------------------------------------------------------------------------------------------------------------------------------------
ProfileView *profileView = [[ProfileView alloc] initWith:nil User:user];
profileView.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:profileView animated:YES];
}
#pragma mark - UISearchBarDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
if ([searchText length] > 0)
{
[self searchUsers:[searchText lowercaseString]];
}
else [self loadPeople];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar_
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[searchBar_ setShowsCancelButton:YES animated:YES];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar_
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[searchBar_ setShowsCancelButton:NO animated:YES];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar_
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[self searchBarCancelled];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar_
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[searchBar_ resignFirstResponder];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBarCancelled
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
searchBar.text = #"";
[searchBar resignFirstResponder];
[self loadPeople];
}
#end
Explanation of what's taking place: The user has added a job as their favorite within another view. Now the user is in the Favorites tab and decides that they no longer want the job as one of their favorites anymore, so they swipe to delete the job. They tap the delete button and the errors below take place...the code works as is, but it also deletes every single job the user has saved as a favorite, instead of just deleting the one job.
My code also gives me an alert of:
Warning: A long-running operation is being executed on the main thread.
Break on warnBlockingOperationOnMainThread() to debug.
#import "JobDetailViewController.h"
#import "MyFavoritesTableViewController.h"
#import "Parse/Parse.h"
#import "Job.h"
#import "JobListViewController.h"
#interface MyFavoritesTableViewController ()
#property (nonatomic, strong) NSString *mainTitle;
#property (nonatomic, strong) NSString *subTitle;
#end
#interface MyFavoritesTableViewController ()
#end
#implementation MyFavoritesTableViewController
{}
#synthesize mainTitle;
#synthesize subTitle;
- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if ([PFUser currentUser]) {
// Custom the table
// The className to query on
self.parseClassName = #"Jobs";
// The key of the PFObject to display in the label of the default cell style
self.textKey = #"Position";
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = YES;
// Whether the built-in pagination is enabled
self.paginationEnabled = YES;
// The number of objects to show per page
self.objectsPerPage = 30;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)objectsWillLoad {
[super objectsWillLoad];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.tableView reloadData];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object: (PFObject *)object
{
static NSString *myJobsTableIdentifier = #"myFavsCell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:myJobsTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myJobsTableIdentifier];
}
// Configure the cell
PFFile *thumbnail = [object objectForKey:#"imageFile"];
PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
thumbnailImageView.image = [UIImage imageNamed:#"AppIcon.png"];
thumbnailImageView.file = thumbnail;
[thumbnailImageView loadInBackground];
UILabel *positionLabel = (UILabel*) [cell viewWithTag:101];
positionLabel.text = [object objectForKey:#"Position"];
UILabel *rotationLabel = (UILabel*) [cell viewWithTag:102];
rotationLabel.text = [object objectForKey:#"Rotation"];
UILabel *locationLabel = (UILabel*) [cell viewWithTag:103];
locationLabel.text = [object objectForKey:#"Location"];
UILabel *typeLabel = (UILabel*) [cell viewWithTag:104];
typeLabel.text = [object objectForKey:#"Type"];
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showDetailedView"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
Job *job = [[Job alloc] init];
JobDetailViewController *destViewController = segue.destinationViewController;
PFObject *object = [self.objects objectAtIndex:indexPath.row];
job.position = [object objectForKey:#"Position"];
job.poc = [object objectForKey:#"POC"];
job.email = [object objectForKey:#"Email"];
job.phone = [object objectForKey:#"Phone"];
job.apply = [object objectForKey:#"Apply"];
job.imageFile = [object objectForKey:#"imageFile"];
job.rotation = [object objectForKey:#"Rotation"];
job.location = [object objectForKey:#"Location"];
job.type = [object objectForKey:#"Type"];
job.clearance = [object objectForKey:#"Clearance"];
job.job_description = [object objectForKey:#"Job_Description"];
job.qualifications = [object objectForKey:#"Qualifications"];
job.originalJob = object;
destViewController.job = job;
}
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([self.objects count] == indexPath.row) {
[self loadNextPage];
} else {
PFObject *photo = [self.objects objectAtIndex:indexPath.row];
NSLog(#"%#", photo);
// Do something you want after selected the cell
}
}
- (PFQuery *)queryForTable
{
PFUser *user = [PFUser currentUser];
PFRelation *relation = [user relationForKey:#"Favorites"];
PFQuery *myquery = [relation query];
if (self.pullToRefreshEnabled) {
myquery.cachePolicy = kPFCachePolicyNetworkOnly;
}
return myquery;
}
#pragma mark - DeleteJobViewDelegate
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
PFUser *user = [PFUser currentUser];
PFRelation *relation = [user relationForKey:#"Favorites"];
PFQuery *myquery = [relation query];
NSArray *array = [myquery findObjects];
for (PFObject *object in array)
{
[relation removeObject:object];
}
[user saveInBackground];
[self.tableView reloadData];
[self loadObjects];
}
#end
The problem is that you are removing all the objects from the Relation:
NSArray *array = [myquery findObjects];
for (PFObject *object in array)
{
[relation removeObject:object];
}
What your code is doing is going though your array and removing each object from the relation.
What you want to do is to delete the job for that cell only. You can get that using the indexPath:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
PFUser *user = [PFUser currentUser];
PFRelation *relation = [user relationForKey:#"Favorites"];
[relation removeObject:[self.objects objectAtIndex:indexPath.row]];
[user saveInBackground];
[self.tableView reloadData];
[self loadObjects];
}
Your second problem:
Warning: A long-running operation is being executed on the main thread. Break on warnBlockingOperationOnMainThread() to debug.
That warning is because findObjects is a synchronous call. You should use the findObjectsInBackground instead. But if you make the changes I gave above, you won't need it.
I have a problem with my TableViewController. There is a custom cell, with a class, and various infos dynamically loaded. My TableViewController appears, but my cell doesn't display, but i can touch this, and my transition with infos are good.
Thanks for your answers.
TableViewController.m
#interface Chat() {
NSMutableArray *messages;
UIRefreshControl *refreshControl;
}
#property (strong, nonatomic) IBOutlet UITableView *tableMessages;
#end
#implementation Chat
NSString *cellIdentifier = #"ChatCell";
- (void)viewDidLoad {
[super viewDidLoad];
[_tableMessages registerClass:[ChatCell class] forCellReuseIdentifier:cellIdentifier];
refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(loadMessages) forControlEvents:UIControlEventValueChanged];
[_tableMessages addSubview:refreshControl];
messages = [[NSMutableArray alloc] init];
[self loadMessages];
}
- (void)loadMessages {
if ([PFUser currentUser] != nil)
{
PFQuery *query = [PFQuery queryWithClassName:PF_MESSAGES_CLASS_NAME];
[query whereKey:PF_MESSAGES_USER equalTo:[PFUser currentUser]];
[query includeKey:PF_MESSAGES_LASTUSER];
[query orderByDescending:PF_MESSAGES_UPDATEDACTION];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error == nil) {
[messages removeAllObjects];
[messages addObjectsFromArray:objects];
[_tableMessages reloadData];
} else [ProgressHUD showError:#"Network error."];
[refreshControl endRefreshing];
}];
}
}
- (void)actionCleanup {
[messages removeAllObjects];
[_tableMessages reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [messages count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ChatCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
[cell bindData:messages[indexPath.row]];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
DeleteMessageItem(messages[indexPath.row]);
[messages removeObjectAtIndex:indexPath.row];
[_tableMessages deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
PFObject *message = messages[indexPath.row];
ChatView *chatView = [[ChatView alloc] initWith:message[PF_MESSAGES_ROOMID]];
[self.navigationController pushViewController:chatView animated:YES];
}
#end
TableViewCell.m
#interface ChatCell() {
PFObject *message;
}
#end
#implementation ChatCell
- (void)bindData:(PFObject *)message_ {
message = message_;
_chatImg.layer.cornerRadius = _chatImg.frame.size.width/2;
_chatImg.layer.masksToBounds = YES;
PFUser *lastUser = message[PF_MESSAGES_LASTUSER];
[_chatImg setFile:lastUser[PF_USER_PICTURE]];
[_chatImg loadInBackground];
_chatUsername.text = message[PF_MESSAGES_DESCRIPTION];
_chatMessage.text = message[PF_MESSAGES_LASTMESSAGE];
NSTimeInterval seconds = [[NSDate date] timeIntervalSinceDate:message.updatedAt];
_chatDate.text = TimeElapsed(seconds);
}
#end
It's because you register the cell using - registerClass:forCellReuseIdentifier:.
If you register it this way you have to construct the view programmatically or load the nib file in ChatCell code.
To solve the problem, do either of these:
Create a nib file containing the view for your table view cell and set the class to ChatCell. Then use - registerNib:forCellReuseIdentifier: to register the nib.
Construct the view programmatically eg. create a UILabel and add it as a subview of ChatCell.
Make the prototype cell in the storyboard and set the cell identifier to ChatCell. Then remove the - registerClass:forCellReuseIdentifier:
Check You are given correct cell Identifier in storyboard. (case sensitive) " ChatCell"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"ChatCell";
ChatCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
[cell bindData:messages[indexPath.row]];
return cell;
}
You are updating the UI on background thread. Try this, in your "loadMessages" method.
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
//update UI here
if (error == nil) {
[messages removeAllObjects];
[messages addObjectsFromArray:objects];
[_tableMessages reloadData];
} else [ProgressHUD showError:#"Network error."];
[refreshControl endRefreshing];
});
}];
This was working fine yesterday and without touching anything it stopped working today. When I run the query to allocate my 'filterEvents' array, 'objects' in the block is empty. Anyone know what's going on?
#import "FilterViewController.h"
#interface FilterViewController ()
#end
#implementation FilterViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.filterTable.dataSource = self;
self.filterTable.delegate = self;
[self performSelector:#selector(retrieveFilteredEvents)];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.filterEvents count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"filterTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSDictionary *tempDict = [self.filterEvents objectAtIndex:indexPath.row];
self.eventTitle = [tempDict objectForKey:#"eventType"];
cell.textLabel.text = self.eventTitle;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *tempDict = [self.filterEvents objectAtIndex:indexPath.row];
NSString *string = [tempDict objectForKey:#"eventType"];
[self.delegate setFilter:string];
[self dismissViewControllerAnimated:YES completion:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"updateParent" object:nil];
}
#pragma mark - Helper Methods
- (IBAction)done:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)retrieveFilteredEvents
{
PFQuery *retrieveEvents = [PFQuery queryWithClassName:#"eventTypes"];
[retrieveEvents orderByAscending:#"eventOrder"];
[retrieveEvents findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
self.filterEvents = [[NSArray alloc] initWithArray:objects];
NSLog(#"%#", self.filterEvents);
}
[self.filterTable reloadData];
}];
}
#end
in my app I'm using Parse.com as the holder of the data on a database and SearchBarDisplayController for research. I have prepared a following to prepare for my table in order to send the data cells in another view controller and works perfectly ... Now I am having a problem ...
How can I create a "prepareforsegue" for the SearchDisplayController, to activate the cells of the search results?
In here you can see the code for "Prepare for Segue" (or another Method) that I made and the data to be passed ...
Some Ideas on this? Thanks so much!
#import "Ricerca.h"
#import "Custom.h"
#import "DettagliProfilo.h"
#interface Ricerca () <UISearchDisplayDelegate, UISearchBarDelegate>
#property (nonatomic, strong) NSMutableArray *searchResults;
#end
#implementation Ricerca
#synthesize searchResults;
- (void)viewDidLoad {
[super viewDidLoad];
[self loadObjects];
self.searchResults = [NSMutableArray array];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// The className to query on
self.parseClassName = #"_User";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = YES;
self.objectsPerPage = 10;
}
return self;
}
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
//[query whereKeyExists:#"username"];
//[query whereKeyExists:#"email"];
[query orderByAscending:#"username"];
if ([self.objects count] == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
return query;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait || UIInterfaceOrientationIsLandscape(interfaceOrientation));
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
UITableViewCell *cell = (UITableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
}
// Configure the cell
UIColor *color = [[UIColor alloc] initWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
cell.detailTextLabel.backgroundColor = color;
cell.textLabel.backgroundColor = color;
if (tableView == self.tableView) {
cell.textLabel.text = [object objectForKey:#"username"];
cell.detailTextLabel.text = [object objectForKey:#"email"];
cell.imageView.image = [UIImage imageNamed:#"unknown"];
PFFile *imageFile = [object objectForKey:#"foto"];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
cell.imageView.image =[UIImage imageWithData:data];
}];
}
else if(tableView == self.searchDisplayController.searchResultsTableView) {
PFObject *searchedUser = [self.searchResults objectAtIndex:indexPath.row];
NSString *content = [searchedUser objectForKey:#"username"];
NSString *email = [searchedUser objectForKey:#"email"];
cell.detailTextLabel.text = email;
cell.textLabel.text = content;
cell.imageView.image = [UIImage imageNamed:#"unknown"];
PFFile *imageFile = [searchedUser objectForKey:#"foto"];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
cell.imageView.image =[UIImage imageWithData:data];
}];
NSLog(#"Content: %#", content);
}
return cell;
}
- (void)callbackLoadObjectsFromParse:(NSArray *)result error:(NSError *)error {
if (!error) {
[self.searchResults removeAllObjects];
NSLog(#"Successfully fetched %d entries", result.count);
[self.searchResults addObjectsFromArray:result];
[self.searchDisplayController.searchResultsTableView reloadData];
} else {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}
-(void)filterResults:(NSString *)searchTerm {
[self.searchResults removeAllObjects];
PFQuery *query = [PFUser query];
[query orderByAscending:#"username"];
[query whereKeyExists:#"email"];
[query whereKey:#"username" containsString:searchTerm];
query.cachePolicy = kPFCachePolicyNetworkOnly;
[query findObjectsInBackgroundWithTarget:self selector:#selector(callbackLoadObjectsFromParse:error:)];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
tableView.rowHeight = 80.0f; // or some other height
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.tableView) {
return self.objects.count;
} else {
return self.searchResults.count;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
[super tableView:tableView didSelectRowAtIndexPath:indexPath];
} else {
[super tableView:tableView didSelectRowAtIndexPath:indexPath];
}
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Check that a new transition has been requested to the DetailViewController and prepares for it
/*if ([segue.identifier isEqualToString:#"Dettaglio"]){
// Capture the object (e.g. exam) the user has selected from the list
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
DettagliProfilo *detailViewController = [segue destinationViewController];
detailViewController.Dettaglio = object;*/
if ([[segue identifier]isEqualToString:#"Dettaglio"])
{
DettagliProfilo *sdvc = (DettagliProfilo *)[segue destinationViewController];
if(self.searchDisplayController.active) {
NSIndexPath *indexPath = [[self tableView] indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
object = (PFObject *)[[self searchResults]objectAtIndex:[[[[self searchDisplayController]searchResultsTableView]indexPathForSelectedRow]row]];
sdvc.Dettaglio = object;
} else {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
DettagliProfilo *detailViewController = [segue destinationViewController];
detailViewController.Dettaglio = object;
}
}
}
#end