So I was able to get the text fields to populate as subviews in my table view for the login. Now I want to reference the username text field and password text field in my login action however the action can not find the variables of the text fields (username and password) PLEASE HELP! This has been driving me nuts! Here is my code.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *CellIdentifier = [self.menuItems objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (indexPath.row == 0) {
UITextField *username = [[UITextField alloc] init];
username.frame = CGRectMake(10, 6, 280, 30);
username.placeholder = #"Username";
cell.tag = 0;
[username addTarget:self action:#selector(login:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:username];
} else {
UITextField *password = [[UITextField alloc] init];
password.frame = CGRectMake(10, 6, 280, 30);
password.placeholder = #"Password";
cell.tag = 1;
[password addTarget:self action:#selector(login:) forControlEvents:UIControlEventTouchUpInside];
[password setSecureTextEntry:YES];
[cell.contentView addSubview:password];
}
return cell;
}
As you can see I created the text fields username and password. However the variables are not being referenced in the action! Anytime the word "username" or "password" shows up, it says "use of undeclared identifier username"/"use of undeclared identifier password". Your help will be greatly appreciated!
-(IBAction)login:(id)sender {
if ([username.text isEqualToString:#""] || [password.text isEqualToString:#""]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oops!" message:#"Please fill in all the fields!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
{
NSString *strURL = [NSString stringWithFormat:#"http://www.mysite.com/myfile.php?username=%#&password=%#",username.text, password.text];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", strResult);
NSString *cont11 = [NSString stringWithFormat:#"http://www.mysite.com/myfile.php?username=%#&password=%#",username.text, password.text];
NSData *cont12 = [NSData dataWithContentsOfURL:[NSURL URLWithString:cont11]];
NSString *cont13 = [[NSString alloc] initWithData:cont12 encoding:NSUTF8StringEncoding];
NSLog(#"%#", cont13);
if ([strResult isEqualToString:#"1"])
{
UIStoryboard *mainStoryboard=[UIStoryboard
storyboardWithName:#"Storyboard" bundle:nil];
AdminPanel *mainView=[mainStoryboard
instantiateViewControllerWithIdentifier:#"admin"];
mainView.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
[self presentViewController:mainView animated:YES completion:nil];
}else
{
// invalid information
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oops!" message:#"You must have entered something wrong! Try again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
}
}
You must create the variables under #interface in your .m file:
#interface YourViewController ()
{
UITextField *username;
UITextField *password;
}
Then take out "UITextField" when you init these variables.
Related
I am writing a simple tableview app, when tapping the row, a alert shows up.
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *rowValue =self.greekLetters[indexPath.row];
// NSString *message=[[NSString alloc] initWithFormat:#"You selected%#!",rowValue];
if (indexPath.row==0) {
NSString *message=[[NSString alloc] initWithFormat:#"This is course aaaaa",rowValue];
}
if (indexPath.row==1) {
NSString *message=[[NSString alloc] initWithFormat:#"This is course aaaaa"];
}
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Course introduction" message:message delegate:nil cancelButtonTitle:#"Return to courses list" otherButtonTitles:nil, nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
However, Xcode doesn't like my if statement here, while the following statement works.
NSString *message=[[NSString alloc] initWithFormat:#"You selected%#!",rowValue];
Could anyone give me an example of how to use the message here please?
This is a problem with scope. You need to declare message before the if statement:
NSString *message;
if (indexPath.row==0) {
message=[[NSString alloc] initWithFormat:#"This is course aaaaa",rowValue];
}
else if (indexPath.row==1) {
message=[[NSString alloc] initWithFormat:#"This is course aaaaa"];
}
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Course introduction" message:message delegate:nil cancelButtonTitle:#"Return to courses list" otherButtonTitles:nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
However, if the course number is determined by the row number do:
NSString *rowValue =self.greekLetters[indexPath.row];
NSString *message = [[NSString alloc] initWithFormat:#"This is course %#",rowValue];
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Course introduction" message:message delegate:nil cancelButtonTitle:#"Return to courses list" otherButtonTitles:nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
You've forgotten to include %# in the first if-statement.
NSString *message= [[NSString alloc] initWithFormat:#"This is course aaaaa %#",rowValue];
By the way, there's no need to do [[NSString alloc] init] at all, just use [NSString stringWithFormat:...]
I have a master-detail program that I add items through a UIAlert to the master list, but when the app quits, the items I added are gone, how can I save the values I added? How would I change to the code below to do this? I've heard you can save to the plist, but I don't know how to use that functionality and I'm not sure its necessary. Thanks!
The value I want to save and reload is "keepValue" which is a NSString property I defined in the header file.
If you are curious how I change the NSDate to a pop up AlertView to add any value you want look here:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
//modified to pop up alertView see: http://stackoverflow.com/questions/11163341/how-do-i-replace-the-date-with-a-writable-title
- (void)insertNewObject:(id)sender
{
UIAlertView *getTitle = [[UIAlertView alloc] initWithTitle:#"Add Search Keyword" message:nil delegate:self
cancelButtonTitle:#"Add"
otherButtonTitles:nil];
getTitle.alertViewStyle = UIAlertViewStylePlainTextInput;
[getTitle show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
NSString * userEnterThisString = [[alertView textFieldAtIndex:0] text];
[_objects insertObject:userEnterThisString atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
self.keepValue = userEnterThisString; //Want to keep after app quits
[self.savedSearchValues addObject:self.keepValue]; //trying to save values to reuse?
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *object = _objects[indexPath.row]; //changed here from default NSDate
cell.textLabel.text = [object description];
return cell;
}
Use NSUserDefaults. There are a lot of answers in StackOverflow.
I got a good response on another site, thank you #Robert Bojor. For anyone else curious I added the save data to file portion of the code to the end of the AlertView method, and I added the read it back in the viewDidLoad (both in the Master View)
Here is final code if you are interested:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
//**********************READ CODE*************************
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0) {
NSString *addedItems = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"addedItems.dta"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:addedItems];
if (fileExists) {
_objects = [NSArray arrayWithContentsOfFile:addedItems];
} else {
// Notify the user the file doesn't exist or try to load it from a cached resource.
}
}
}
//modified to pop up alertView see: http://stackoverflow.com/questions/11163341/how-do-i-replace-the-date-with-a-writable-title
- (void)insertNewObject:(id)sender {
UIAlertView *getTitle = [[UIAlertView alloc] initWithTitle:#"Add Search Keyword" message:nil delegate:self cancelButtonTitle:#"Add" otherButtonTitles:nil];
getTitle.alertViewStyle = UIAlertViewStylePlainTextInput;
[getTitle show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
NSString * userEnterThisString = [[alertView textFieldAtIndex:0] text];
[_objects insertObject:userEnterThisString atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
self.keepValue = userEnterThisString;
//**********************SAVE CODE*************************
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *addedItems = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"addedItems.dta"];
// The file name and extension can be changed at will
[_objects writeToFile:addedItems atomically:YES];
}
I try to understand the application to save the data. I have a custom object.
#interface CellObject : NSObject <NSCoding>
#property (nonatomic, strong) NSString *links;
#property (nonatomic, strong) NSString *title;
#property (assign) BOOL isFavorite;
#end
#import "CellObject.h"
#implementation CellObject
#synthesize title, links;
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:title forKey:#"title"];
[aCoder encodeObject:links forKey:#"links"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self){
[self setTitle:[aDecoder decodeObjectForKey:#"title"]];
[self setLinks:[aDecoder decodeObjectForKey:#"links"]];
}
return self;
}
And the controller to the table in cells which must be my objects.
#import "SettingsViewController.h"
#import "SettingsCell.h"
#import "CellObject.h"
#define kFileName #"archive"
#define kDataKey #"Data"
#implementation SettingsViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
self.title = #"Settings";
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:#"Helvetica" size:20.0f], NSFontAttributeName, nil] forState:UIControlStateNormal];
}
return self;
}
-(NSString *)dataFilePath {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFileName];
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
[_rssObjectArray removeAllObjects];
_rssObjectArray = nil;
if(!_rssObjectArray)
{
_rssObjectArray = [[NSMutableArray alloc]init];
}
_resourceTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
[_resourceTV setAutoresizesSubviews:YES];
[_resourceTV setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
[_resourceTV setDataSource:self];
[_resourceTV setDelegate:self];
[self.view addSubview:_resourceTV];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showAlert)];
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSMutableData* data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
CellObject *cellObj = [unarchiver decodeObjectForKey:kDataKey];
[unarchiver finishDecoding];
}
}
-(void)applicationWillResignActive:(NSNotification *)notification
{
CellObject *cellObj = [[CellObject alloc] init];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:cellObj forKey:kDataKey];
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];
}
- (void)showAlert
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Enter name" message:#"And internet adress" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
UITextField *bottomField = [alertView textFieldAtIndex:0];
[bottomField setPlaceholder:#"Name"];
UITextField *footerField = [alertView textFieldAtIndex:1];
[footerField setPlaceholder:#"Internet adress"];
footerField.secureTextEntry = NO;
alertView.tag = -1;
[alertView show];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _rssObjectArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = [SettingsCell cellIdentifier];
SettingsCell *sCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!sCell)
{
sCell = [[SettingsCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
CellObject *object = [_rssObjectArray objectAtIndex:indexPath.row];
sCell.linkLabel.text = object.links;
sCell.nameLabel.text = object.title;
sCell.favorite.selected = object.isFavorite;
return sCell;
}
//change rows in table
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[_rssObjectArray removeObjectAtIndex:indexPath.row];
[_resourceTV deleteRowsAtIndexPaths:#[indexPath] withRowAnimation: UITableViewRowAnimationTop];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex && (alertView.alertViewStyle == UIAlertViewStyleLoginAndPasswordInput))
{
CellObject *object = nil;
if (alertView.tag == -1) {
object = [[CellObject alloc]init];
[_rssObjectArray addObject:object];
} else {
object = [_rssObjectArray objectAtIndex:alertView.tag];
}
object.links = [[alertView textFieldAtIndex:0] text];
object.title = [[alertView textFieldAtIndex:1] text];
[_resourceTV reloadData];
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Enter name" message:#"And internet adress" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
UITextField *bottomField = [alertView textFieldAtIndex:0];
[bottomField setPlaceholder:#"Name"];
UITextField *footerField = [alertView textFieldAtIndex:1];
[footerField setPlaceholder:#"Internet adress"];
footerField.secureTextEntry = NO;
CellObject *cellObj = [_rssObjectArray objectAtIndex:indexPath.row];
bottomField.text = cellObj.links;
footerField.text = cellObj.title;
alertView.tag = indexPath.row;
[alertView show];
}
#end
On the Internet find tutorials, but they are not very helpful, tell me how to do so would object persists after restarting the application, they remained in the cells?
In your viewDidLoad:
- (void)viewDidLoad
{
// ...
if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) { // Check if the file exist.
NSMutableData* data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]]; // Retrieve the data from the file
self.rssObjectArray = [[NSKeyedUnarchiver unarchiveObjectWithData:data] mutableCopy];
}
}
And your
- (NSString *)dataFilePath
{
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"CustomFeed.plist"];
/*BOOL result = [NSKeyedArchiver archiveRootObject:self.rssObjectArray toFile:path];
// This line above erase the file when it's called, remove all the code i commented.
if(result == YES)
{
NSLog(#"Array saved");
}*/
return path;
}
With these modifications, i tested your application and it's work.
I am using UITableView. And if there is no network connection then there will be exception thrown in viewDidload. My viewDidLoad function is:
#try {
NSLog(#"Request URL = %#",URLString);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:URLString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSDictionary *tableData = [NSJSONSerialization JSONObjectWithData:response
options:0
error:&jsonParsingError];
// Grab whole data with data field in JSON
// responseArray = [tableData objectForKey:#"data"];
responseArray = [[NSMutableArray alloc]initWithArray:[tableData objectForKey:#"data"]];
for(int i = 0; i < responseArray.count; i++)
{
NSArray * tempArray = responseArray[i];
responseArray[i] = [tempArray mutableCopy];
}
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(280.0, 0.0, 40.0, 40.0)];
[btn setImage:[UIImage imageNamed:#"sort_icon.png"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(showActionSheet) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barbutton = [[UIBarButtonItem alloc]initWithCustomView:btn];
self.navigationItem.rightBarButtonItem = barbutton;
}
#catch (NSException *exception)
{
exceptionOccured = YES;
NSLog(#"Exception Ocurred");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Error in connectivity" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
In cellForRowAtIndexPath I am doing this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
#try {
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
tempDict = [responseArray objectAtIndex:indexPath.row];
return cell;
}
#catch (NSException *exception)
{
NSLog(#"Error in CEll Create");
NSLog(#"Draw Alert");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Error in connectivity" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
and in AlertViewDelegate Function I am doing
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
[self.navigationController popViewControllerAnimated:YES];
}
Now problem is that it is not showing the Alert whenever there is an exception and re-throws the exception and shows the Error
Thread 1: EXC_BAD_ACCESS(code=2, address=0x2)
Any help will be appreciated...
You should avoid throwing exceptions in your code.
First of all you could use Reachability Class to determine whether or not an active internet connection is available.
I would definitively recommend using the NSURLConnectionDelegate protocol for URL connections. So you can use the better asynchronous programming style.
The problem is somewhere else. When - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath is called it means the system needs the tableView to be reloaded. Therefore, you should not check for data inside that function. When you enter this function, you should be sure that your data is ok.
What you have to do is firstly check your data in a specific function:
-(void)CheckData(NSArray *responseArray) {
#try {
//Retrieve your data & check if its valid
self.dataArray = responseArray;
[self.tableView reloadData];
}
#catch (NSException *exception)
{
NSLog(#"Error in check Data");
NSLog(#"Draw Alert");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Error in connectivity" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
Then, implement your data source delegates:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.dataArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease] ;
}
//TODO: Init your cell using your self.dataArray content
return cell;
}
I would recommend import this SystemConfiguration framework and use the same. This will check whether network connection is available or not. Below is the simple code:-
#import <SystemConfiguration/SystemConfiguration.h>
-(void)yourMethod
{
SCNetworkConnectionFlags flags = 0;
if (yourhostname && [yourhostname length] > 0)
{
flags = 0;
BOOL found = NO;
SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [yourhostname UTF8String]);
if (reachabilityRef)
{
found = SCNetworkReachabilityGetFlags(reachabilityRef, &flags)
&& (flags & kSCNetworkFlagsReachable)
&& !(flags & kSCNetworkFlagsConnectionRequired);
CFRelease(reachabilityRef);
reachabilityRef = NULL;
}
if (found)
{
NSLog(#"Connection available");
}
else
{
NSLog(#"Connection not available");
}
}
I have a very tricky situation. And all things I have did programmatically.
1) I have UITableView.
2) In every cell of this tableview I have one uibutton.
3) On click of UIButton I want to show a UIAlertView, Which have yes and not buttons.
4) On click of yes button I want to delete that cell whose UIButton had shown up this alertview.
Below is my code snippet:
- (void) removeFriends:(id)sender
{
/*
I want to show alertview at here...
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"CONFIRM",nil) message:NSLocalizedString(#"REMOVE_FRIEND",nil) delegate:self cancelButtonTitle:#"No" otherButtonTitles:#"Yes", nil];
alert.tag = 21;
alert.accessibilityIdentifier = #"Remove";
[alert show];
*/
UIButton *btn = (UIButton*)sender;
int indx = btn.tag;
NSString *friend_id = [friendsId valueForKey:[NSString stringWithFormat:#"%d",indx]];
// URL creation
NSString *path = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"path"];
NSString *address = [NSString stringWithFormat:#"%#%#%#", path,#"users/",usrId];
NSURL *URL = [NSURL URLWithString:address];
// request creation
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:60.0];
[request setHTTPMethod:#"DELETE"];
responseData = [[NSMutableData alloc] init];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
UITableViewCell *buttonCell = (UITableViewCell *)[btn superview];
NSIndexPath* pathOfTheCell = [self.table indexPathForCell:buttonCell];
[self.table deleteRowsAtIndexPaths:[NSArray arrayWithObjects:pathOfTheCell, nil] withRowAnimation:UITableViewRowAnimationFade];
[self viewDidLoad];
[self.table reloadData];
}
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if([alertView.accessibilityIdentifier isEqualToString:#"Remove"])
{
if (buttonIndex == 1)
{
// here want to make call to server
}
}
}
Just put this:
NSString *friend_id = [friendsId valueForKey:[NSString stringWithFormat:#"%d",indx]];
// URL creation
NSString *path = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"path"];
NSString *address = [NSString stringWithFormat:#"%#%#%#", path,#"users/",usrId];
NSURL *URL = [NSURL URLWithString:address];
NSLog(#"%#",address);
// request creation
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:60.0];
[request setHTTPMethod:#"DELETE"];
responseData = [[NSMutableData alloc] init];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
UITableViewCell *buttonCell = (UITableViewCell *)[btn superview];
NSIndexPath* pathOfTheCell = [self.table indexPathForCell:buttonCell];
[self.table deleteRowsAtIndexPaths:[NSArray arrayWithObjects:pathOfTheCell, nil] withRowAnimation:UITableViewRowAnimationFade];
[self viewDidLoad];
[self.table reloadData];
into this:
if([alertView.accessibilityIdentifier isEqualToString:#"Remove"]){
if (buttonIndex == 1) {
// here want to make call to server
}
}
and create a property in your .h file which will be holding the id of the button which had been pressed. Like this:
//in your .h file
#property (nonatomic, strong) NSString *yourId;
and in your button-action just set it like this:
self.yourId = [friendsId valueForKey:[NSString stringWithFormat:#"%d",indx]];
In the first code snippet I guess you will have to replace usrId with self.yourId, so it will be
NSString *address = [NSString stringWithFormat:#"%#%#%#", path,#"users/",self.yourId];
EDIT:
Remove this:
UITableViewCell *buttonCell = (UITableViewCell *)[btn superview];
and change this:
NSIndexPath* pathOfTheCell = [self.table indexPathForCell:buttonCell];
to this:
NSIndexPath* pathOfTheCell = [NSIndexPath indexPathForRow:self.yourId]
self.yourID is the indexPath.row value which was saved in your button.tag property.
In this situation, you can assign index of cell inalertview tag and use this tag to perform your operation.
Thanks
Update:
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if([alertView.accessibilityIdentifier isEqualToString:#"Remove"])
{
if (buttonIndex == 1)
{
// here want to make call to server
// User alertView.tag as index to delete
}
}
}
view.h
#interface MyReservationViewController : UIViewController
{
int Delete_row;
}
view.m
- (IBAction)delete_btn:(id)sender
{
UIButton *buttontag = (UIButton *)sender;
//NSLog(#"%d",buttontag.tag);
Delete_row = buttontag.tag;
UIAlertView *Alert = [[UIAlertView alloc]initWithTitle:#"Delete Reservation" message:#"Are you sure to want Delete Reservation ??" delegate:self cancelButtonTitle:#"Delete" otherButtonTitles:#"Cancel",nil];
Alert.tag=1;
[Alert show];
[Alert release];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(alertView.tag==1)
{
if(buttonIndex == 0)
{
NSLog(#"%d",Delete_row);
//delete cell
[Arr removeObject:Delete_row];
[tbl reloadData];
}
}
}
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if([alertView.accessibilityIdentifier isEqualToString:#"Remove"])
{
if (buttonIndex == 1)
{
// add server call to delete the relevant data
// and then refresh your array that you are using in cellForRowAtIndex
//and reload table. thats it.
}
}