UIAlertView confirm delete button - ios

I have a tableview, and a delete function. Now I want an UIAlertView with a confirmation.
This is my code what I have now:
(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
AgendaModel* agenda = _meeting.agenda[indexPath.row] ;
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:agenda.id,#"id",agenda.name,#"name", nil];
NSString *message = [NSString stringWithFormat:#"Are you sure that you want to delete : %#?", agenda.name];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning"
message:message
delegate:self
cancelButtonTitle:#"Close"
otherButtonTitles:#"Delete", nil];
[alert show];
}
}
It give's a popup, but because I didn't say to delete it isn't working. I want my app to do this code after the button Delete is pressed:
NSString *delete_url = [NSString stringWithFormat:#"RestAgendas/delete.json"];
[_meeting.agenda removeObject:agenda];
[self.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[JSONAPI getWithPath:delete_url andParams:dict completion:^(id json, JSONModelError *err) {
NSLog(#"%#", json);
}];
Where can I define actions to buttons in a UIAlertView?
Sorry for the messy question, hope you guys understand my intentions

You should avoid using AlertView (it's deprecated) and switch to UIAlertController.
It is more generic and replaces old alertView and actionSheet.
See the documetation
and tutorial in swift or tutorial in objC.

Related

Tableview display alert error

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:...]

iOS How to save addButton additions to Master View in Master-Detail Template after quitting app

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];
}

Display an alert on Swipe Delete in iOS

I'm a beginner in iOS. I'm performing a swipe delete option. I want to display an alert view before deleting the row. How can i perform this action.
- (void)tableView:(UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%#",collisionsArray);
if (editingStyle == UITableViewCellEditingStyleDelete)
{
NSUserDefaults *userinfo = [NSUserDefaults standardUserDefaults];
NSString *userId = [userinfo valueForKey:#"user_id"];
if(userId!=nil)
{
NSDictionary* dict = [collisionsArray objectAtIndex:indexPath.section];
collisionId = [NSString stringWithFormat:#"%#",[dict valueForKey:#"collisionId"]];
NSLog(#"%#",collisionId);
// removes saved datas from database
BOOL result = [database removeCollisionDetails:collisionId:#"accident_report"];
if(result)
{
[[SHKActivityIndicator currentIndicator]
displayCompleted:NSLocalizedString(#"val_sucess_vehicle", nil)];
[self.navigationController popViewControllerAnimated:YES];
}
else
{
[[SHKActivityIndicator currentIndicator]
displayCompleted:NSLocalizedString(#"val_error", nil)];
}
}
}
[self.tableView reloadData];
}
For this you can just display an alet view in:
if (editingStyle == UITableViewCellEditingStyleDelete){
// Show your alert view
// Set its delegate to self
}
Now you have to do something like:
#pragma mark ---- Delegate for alertview ----
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSUserDefaults *userinfo = [NSUserDefaults standardUserDefaults];
NSString *userId = [userinfo valueForKey:#"user_id"];
if(userId!=nil)
{
NSDictionary* dict = [collisionsArray objectAtIndex:indexPath.section];
collisionId = [NSString stringWithFormat:#"%#",[dict valueForKey:#"collisionId"]];
NSLog(#"%#",collisionId);
// removes saved datas from database
BOOL result = [database removeCollisionDetails:collisionId:#"accident_report"];
if(result)
{
[[SHKActivityIndicator currentIndicator] displayCompleted:NSLocalizedString(#"val_sucess_vehicle", nil)];
[self.navigationController popViewControllerAnimated:YES];
}
else
{
[[SHKActivityIndicator currentIndicator] displayCompleted:NSLocalizedString(#"val_error", nil)];
}
}
}
-(void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Warring" message:#"Are You Sure?" delegate:self cancelButtonTitle:#"No" otherButtonTitles:#"Yes ", nil];
[alert show];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0) {
}else if (buttonIndex == 1){
NSIndexPath *indexPath=[_UserTableView indexPathForSelectedRow];
[showUData removeObjectAtIndex:indexPath.row]; //showUData NSMutableArray
[_UserTableView reloadData];
[storeData setObject:showUData forKey:#"SendData"]; //storeData NSUserDefault
[storeData synchronize];
}
}
Use UIAlertView and only delete if the user confirms. Update your code to :
if (editingStyle == UITableViewCellEditingStyleDelete)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Hello World!"
message:#"Are you sure ?"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
Implement the UIAlertViewDelegate and move the original delete code to the delegate method where you detect which button has been tapped.

Not Able to show UIAlert on Exception

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");
}
}

how to call to tableView from class method

Ive been having a lot of troubles deleting the cell from the tableView. I have 3 buttons in a sliding cell thats revealed when swiped over, the methods that call the swiping are in JBSliderViewController. In order to access the class method embedded in the homeViewController i created a instance method inside the JBSliderViewController -(void)callDeleteFound to call my +(void)deleteFound thats inside my homeViewController.
My issue now is i cant get access to my tableView to call – deleteRowsAtIndexPaths:withRowAnimation:
As well as currentTable is returning null
any suggestions?
inside JBSliderController
- (void)callDeletefound {
[homeViewController deleteFound];
}
inside homeViewController
+ (void)deleteFound {
NSUserDefaults *userSessionData = [NSUserDefaults standardUserDefaults];
NSString *userID = [userSessionData stringForKey:#"userID"];
NSString *authKey = [userSessionData stringForKey:#"authKey"];
NSString *appVersion = [userSessionData stringForKey:#"appVersion"];
NSString *versionedURL = [NSString stringWithFormat:#"/ios/%#/", appVersion];
NSURL *url = [NSURL URLWithString:#"http://website.com"];
NSString *postPath = [NSString stringWithFormat:#"%#deletefind.php", versionedURL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
userID, #"userid",
[MyClass friendID], #"friendid",
authKey, #"tempAuth",
nil];
[httpClient postPath:postPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
[SVProgressHUD showSuccessWithStatus:#"Removed from notifications"];
NSMutableArray *notificationArray = [[NSUserDefaults standardUserDefaults] objectForKey:#"notificationsArray"];
NSMutableArray *arrayThatYouCanRemoveObjects = [NSMutableArray arrayWithArray:notificationArray];
NSLog(#"%#", [MyClass cellNum]);
NSInteger *num = [[MyClass cellNum] integerValue];
[arrayThatYouCanRemoveObjects removeObjectAtIndex:num];
[currentTable deleteRowsAtIndexPaths:openedCellIndexPath withRowAnimation:UITableViewRowAnimationLeft];
[currentTable reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[HTTPClient Error]: %#", error.localizedDescription);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Fail" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}];
}
In order to get the swipe affect you need to implement the table view delegate
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
method, this will provide access to the swipe interaction for deletion. I typically provide an edit interaction as well for tableviews where deletion is possible since the swipe interaction tends to be a little bit hidden from users.
As an example:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView beginUpdates];
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Do whatever data deletion you need to do...
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
}
[tableView endUpdates];
}
Hope that helps.
NSArrays are inmmutable, that means you can't add or remove elements, hence your object doesn't have a removeObjectAtIndex: method.
Check your property to see if its an NSArray instead of an NSMutableArray.
Check that the object in that pointer is in fact an NSMutableArray.
To assign an NSArray to your variable first create an NSMutableArray from it using the arrayWithArray: method.

Resources