Display alert if no recipients are selected iOS - ios

I have a page where we select recipients (who are friends) to send an image to. but if no recipients are selected we can still send the message. i want it so that if no recipients are selected we can show a UIAlertView. for me its not working when i try to display an alert please see my code below.
.h
#property (nonatomic, strong) NSArray *friends;
#property (nonatomic, strong) PFRelation *friendsRelation;
#property (nonatomic, strong) NSMutableArray *recipients;
- (IBAction)send:(id)sender;
.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.recipients = [[NSMutableArray alloc] init];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.friendsRelation = [[PFUser currentUser] objectForKey:#"friendsRelation"];
PFQuery *query = [self.friendsRelation query];
[query orderByAscending:#"username"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"Error %# %#", error, [error userInfo]);
}
else {
self.friends = objects;
[self.tableView reloadData];
}
}];
//display camera modally etc......
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
PFUser *user = [self.friends objectAtIndex:indexPath.row];
cell.textLabel.text = user.username;
if ([self.recipients containsObject:user.objectId]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
#pragma mark - Table view delegate
- (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];
}
NSLog(#"%#", self.recipients);
}
here is the part where i try to display my alert
- (IBAction)send:(id)sender {
if (!self.recipients) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Select some friends" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
} else {
[self uploadMessage];
//we upload the message in method to parse.com
}
}
it does not seem to show for some reason so we can send messages to no one. how can i show the alert view?

Try this. Check objects of recipients is equal to 0 or not.
- (IBAction)send:(id)sender {
if ([self.recipients count]==0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Select some friends" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
} else {
[self uploadMessage];
//we upload the message in method to parse.com
[self.tabBarController setSelectedIndex:1];
}
}

The problem with your code is the condition that you are checking::
if (!self.recipients)
here self.recipients will always give true value as it will look for memory address of this object, which you have assigned to it in your viewDidLoad method.
You have to check for the count of the array in your scenario.

Related

Updating Parse Data in UiTableview

I have a tableview that is full of current user data that is stored in parse. I want to be able to click on the cell of the parse data and be able to edit that data in a edit screen (which is just going to be the screen where you save the data from) then be able to save it and it update in the parse class on the cloud. I saw this code on the parse developer website regarding updating objects Updating Objects Here
PFQuery *query = [PFQuery queryWithClassName:#"GameScore"];
[query getObjectInBackgroundWithId:#"xWMyZ4YEGZ"
block:^(PFObject *gameScore, NSError *error) {
gameScore[#"cheatMode"] = #YES;
gameScore[#"score"] = #1338;
[gameScore saveInBackground];
}];
But the problem is that in the
[query getObjectInBackgroundWithId:#"xWMyZ4YEGZ"
block:^(PFObject *gameScore, NSError *error)
Is a query by the specific ObjectId that is stated. How can I change this so that when a user clicks on the tableview cell the query runs by that specific ObjectId in parse so that I can edit the strings associated with the ObjectId. Any tutorials or guidance is really appreciated!
Here is my Tableview.m
#implementation ViewController
- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if (self) {
// Custom the table
// The className to query on
self.parseClassName = #"rep";
// The key of the PFObject to display in the label of the default cell style
self.textKey = #"name";
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = YES;
// Whether the built-in pagination is enabled
self.paginationEnabled = NO;
// The number of objects to show per page
//self.objectsPerPage = 10;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(refreshTable:)
name:#"refreshTable"
object:nil];
{
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:#"Delete Cannot Be Undone" message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[Alert show];
}
}
- (void)refreshTable:(NSNotification *) notification
{
// Reload the recipes
[self loadObjects];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"refreshTable" object:nil];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (PFQuery *)queryForTable
{
PFQuery *query = [PFQuery queryWithClassName:#"rep"];
[query whereKey:#"user" equalTo:[PFUser currentUser]];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
static NSString *simpleTableIdentifier = #"RepCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
// Configure the cell
UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
nameLabel.text = [object objectForKey:#"name" ];
UILabel *time = (UILabel*) [cell viewWithTag:102];
time.text = [object objectForKey:#"time"];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Remove the row from data model
PFObject *objectToDel = [self.objects objectAtIndex:indexPath.row];
[objectToDel deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:#"Item Was Deleted Successfully. Pull Down to Refresh Tab" message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[Alert show];
[self loadView];
}
];
}
- (void) objectsDidLoad:(NSError *)error
{
[super objectsDidLoad:error];
NSLog(#"error: %#", [error localizedDescription]);
}

UITableViewCell staying empty

I am trying to fill a UITableView with the objects of an NSMutableArray which is filled from a table in Parse. The array is definitely being filled (I checked its contents with an NSLog), but the table is staying empty. I have tried A LOT of different ways including the following:
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
PFObject *postsObject = [postsArray objectAtIndex:indexPath.row];
cell.textLabel.text = [postsObject objectForKey:#"message"];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
if (!cell) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (tableView == table) {
cell.textLabel.text = [postsArray objectAtIndex:indexPath.row];
}
return cell;
}
and the much simpler
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = [table dequeueReusableCellWithIdentifier:#"Cell"];
cell.messageLabel.text = [NSString stringWithFormat:[postsArray objectAtIndex:[indexPath row]]];
return cell;
}
Does anyone have any ideas?
Thanks in advance :)
EDIT:
My dataSource methods are:
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return postsArray.count;
}
EDIT #2:
My code I'm using to fill my array and reload my tableView
PFQuery *findData = [PFQuery queryWithClassName:#"AllPosts"];
[findData setLimit:1000];
[findData findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error == nil) {
for (PFObject *object in objects) {
PFObject *post = object[#"content"];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:post, nil];
postsArray = array;
[table reloadData];
}
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Unable To Load" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}];
You are doing it wrong , you are replacing the array with new data whenever you are finding a PFObject in objects, your code should be like this:-
//first alloc your array
postsArray=[[NSMutableArray alloc] init];
//Logic goes here
PFQuery *findData = [PFQuery queryWithClassName:#"AllPosts"];
[findData setLimit:1000];
[findData findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error == nil) {
for (PFObject *object in objects) {
PFObject *post = object[#"content"];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:post, nil];
[postsArray addObject:array];
[table reloadData];
}
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Unable To Load" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}];
You also need to check if the cell object is actually returned. Also put in the following code after the call to dequeueReusableCellWithIdentifier:
if(!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
This would solve your problem

UITableView Won't Display Data

I have a UITableView and it refuses to show any data, Xcode isn't showing any errors or warnings. Not sure why this is because the same code was working in a different app (obviously the names of array and tableview were different). I have the delegate and datasource both set as the view view-controller. If there is anything i missed please tell me!
Here is my code:
#import "ViewController.h"
#interface UIViewController ()
#end
#implementation ViewController
#synthesize CafeTableView;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self performSelector:#selector(RetriveData)];
[CafeTableView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)RetriveData {
PFQuery *query = [PFQuery queryWithClassName:#"CafeList"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSLog(#"%#",objects);
NSLog(#"Successfully retrieved %d Cafes.", objects.count);
cafeListArry = [[NSArray alloc] initWithArray:objects];
}else{
UIAlertView *theAlert = [[UIAlertView alloc] initWithTitle:#"Error"
message:(#"There has been an error loading the Cafe List Please Try Again!")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[theAlert show];
NSLog(#"%#",error);
}
}];
[CafeTableView reloadData];
}
//-------------------TABLE VIEW-----------------------
- (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 cafeListArry.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CafeCell";
CafeListCell *cell = [CafeTableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
PFObject *tempObject = [cafeListArry objectAtIndex:indexPath.row];
cell.title.text = [tempObject objectForKey:#"CafeName"];
cell.detail.text = [tempObject objectForKey:#"NumberOfStars"];
return cell;
}
#end
Move your call to reloadData inside the block as others have suggested and change the if condition as follows:
- (void)RetriveData {
PFQuery *query = [PFQuery queryWithClassName:#"CafeList"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (objects) {
NSLog(#"%#",objects);
NSLog(#"Successfully retrieved %d Cafes.", objects.count);
cafeListArry = [[NSArray alloc] initWithArray:objects];
[CafeTableView reloadData]; // HERE
}else{
UIAlertView *theAlert = [[UIAlertView alloc] initWithTitle:#"Error"
message:(#"There has been an error loading the Cafe List Please Try Again!")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[theAlert show];
NSLog(#"%#",error);
}
}];
}
Also, as suggested by Lyndsey in the comments, change the following line
cell.detail.text = [tempObject objectForKey:#"NumberOfStars"];
to
cell.detail.text = [[tempObject objectForKey:#"NumberOfStars"] stringValue];
because you said that it's a number, not a string.
Please check the delegates are connected in xib file or not if not then please connect properly and please call the [tableview reloadData]; method at the time when you want bind the data with table

Reload data after logging in

I have a left slide menu powered by AMSlideMenu library that displays a tableview with menu items.
AMSlideMenuLeftTableViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
cell.textLabel.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:18];
cell.textLabel.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"loggedUser"] != nil) {
if (indexPath.row == 0) { cell.textLabel.text = [NSString stringWithFormat:#"Hi, %#", [[NSUserDefaults standardUserDefaults] objectForKey:#"loggedUser"]]; }
if (indexPath.row == 1) { cell.textLabel.text = #"Contact"; }
} else {
if (indexPath.row == 0) { cell.textLabel.text = #"Log in"; }
if (indexPath.row == 1) { cell.textLabel.text = #"Contact"; }
}
}
LoginViewController.m
- (IBAction)loginButtonPressed:(id)sender {
if(![self.usernameTextField.text isEqual: #""] && ![self.passwordTextField.text isEqual:#""]){
for (UITextField *eachTextfield in self.view.subviews)
[eachTextfield resignFirstResponder];
PFQuery *query = [PFQuery queryWithClassName:#"UsersClass"];
[query whereKey:#"Username" equalTo:self.usernameTextField.text];
[query whereKey:#"Password" equalTo:self.passwordTextField.text];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// The find succeeded.
if (objects.count > 0){
[self dismissViewControllerAnimated:YES completion:nil];
//Get the username and save it as "loggedUser" for later use
[[NSUserDefaults standardUserDefaults] setObject:self.usernameTextField.text forKey:#"loggedUser"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self performSegueWithIdentifier:#"showDetail" sender:self];
}else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:NSLocalizedString(#"The username or password are incorrect", nil) delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:NSLocalizedString(#"Both fields are required", nil) delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
However, after logging in, the menu does not refresh and keeps displaying the wrong cell.textLabel.text. It works if I close and open again the application, but obviously there has to be another way of solving this.
I have tried [tableView reloadData] but this does not work. I have tried it on viewDidLoad and viewWillAppear without success.
Appreciate any help. Thanks
Here is what you need to do. In your loginButtonPressed method in case of a successful login post a notification like this:
NSNotification *loginNotification = [NSNotification notificationWithName:#"USER_DID_LOGIN" object:nil];
[[NSNotificationCenter defaultCenter] postNotification:loginNotification];
In your view controller with tableView do this:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(updateOnLogin:) name:#"USER_DID_LOGIN" object:nil];
}
- (void)updateOnLogin:(NSNotification*)notification
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
Whenever user logs in successfully, your view controller will receive a notification, and it will reload the tableView.

Retrieving objects from parse into table view cell

I have created an object and saved it to the backend named NewCar and there are 4 strings attached to which are year, make, model, horsepower I'm having troubles pulling the data from parse and placing it into my table here is a few pieces of my code.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
PFQuery *query = [PFQuery queryWithClassName:#"NewCar"];
[query whereKey:#"year" equalTo:[[PFUser currentUser] objectId]];
[query orderByAscending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
} else {
self.cars = objects;
[self.tableView reloadData];
}
}];
}
#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.cars count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"garageCell";
garageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[garageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.usernameDisplay.text = [[PFUser currentUser] objectForKey:#"username"];
//I need to display the year, make and model below here.
cell.carYearLabel.text = [[PFObject objectWithClassName:#"NewCar"] objectForKey:#"year"];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 236;
}
I am able to display the username in my custom cell, but can't figure out how to display the year, make and model values. Any help would be much appreciated.
I have been looking through the documentation in Parse and can't seem to figure it out just in case you are wondering if I tried there.
I also want to add in the code where I added the object to Parse this might help in figuring this out as well.
- (IBAction)save:(id)sender {
NSString *year = self.carYear.text;
NSString *make = self.carMake.text;
NSString *model = self.carModel.text;
NSString *horsepower = self.carHorsepower.text;
if ([year length] == 0 || [make length] == 0 || [model length] == 0 || [horsepower length] == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:#"You might have missed a field" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
} else {
PFObject *newCar = [PFObject objectWithClassName:#"NewCar"];
newCar[#"year"] = year;
newCar[#"make"] = make;
newCar[#"model"] = model;
newCar[#"horsepower"] = horsepower;
[newCar saveInBackground];
[self.navigationController popToRootViewControllerAnimated:YES];
}
}
Okay so instead of using
cell.carYearLabel.text = [[PFObject objectWithClassName:#"NewCar"] objectForKey:#"year"];
You can use the following
cell.carYearLabel.text = [self.cars objectForKey:#"NewCar"] valueForKey:#"year"];

Resources