Objective-C: UIAlert or asking for confirmation


xcode While start XCoding, I faced a new challenge : how to create modal, single use confirmation dialogs? So after some digging in the internet, I found out that this can be actually done pretty simple and elegant. This will be very useful if you want to display some deletion confirmation or ask for user permission to use the camera or GPS sensor. All you have to do is just create a UIAlert and the IBAction hooked up to your “Nuclear launch” button, and then have its delegate decide whether to destroy the world or not.

In the header file you have to add this declaration of the action performed when the fatal button is clicked:

- (IBAction) btnLaunchNuclearStrikeClicked:(id)sender
- (IBAction) deleteButtonClicked:(id)sender;


// And inside this action, create an alert with two buttons and show it:
- IBAction) btnLaunchNuclearStrikeClicked:(id)sender{ 
  // create a simple alert with an OK and cancel button
  UIAlertView *alert = [[UIAlertView alloc]
    initWithTitle:@"Do you really want to start the End of World?"
	message:nil
	delegate:self
	cancelButtonTitle:@"No, cancel Red Day"     
	otherButtonTitles:@"Yes, initia", nil];
  [alert show];
  [alert release];
}

What’s important to notice is how the delegate is set to self. So this alert will be modal (indeed, is blocking the main thread — the user has to press a button to continue using the application). After the user presses a button, the alert will call the following method on the self object:

- (void)alertView:(UIAlertView *)alertView 
    clickedButtonAtIndex:(NSInteger)buttonIndex

Now we have to understand some conventions :the buttonIndex will be equal to 1 if the OK button was pressed, and nil otherwise, so we can handle the launch nuclear strike operation in here.

- (void)alertView:(UIAlertView *)alertView 
    clickedButtonAtIndex:(NSInteger)buttonIndex{
  if (buttonIndex == 1) {
    // Launch nuclear strike !
  } else {
	// be nice with the world, maybe initiate some Ecological action as a bonus
  }
}

That’s it, folks! A small step for you, big improvement in user experience – add confirmations to the more severe operations in your iPhone app.

Leave a comment

Your email address will not be published. Required fields are marked *