Select Article.

Site Search

Search Articles.

iPhone: Creating a custom UIAlertView Busy Dialog

Wednesday 31 Mar 2010 18:59

One of the major problems facing iPhone developers, especially those coming from a Windows environment  is the lack of dialogs. We use dialogs when we require user input or need to display feedback.  I recently needed to display a 'Please Wait' dialog whilst downloading files from a web server, and found a way to do this using a UIAlertView.

The iPhone's UIAlertView generally displays an on screen message allowing the user to select one or more options as in the image below.

In the case of a "Please Wait" dialog we don't require any buttons and need to insert a UIActivity indicator inside the dialog. Generally speaking you can embed most UI elements inside a UIAlertView, but to do this you need to expand the dialog, which you can do by inserting a series of returns in the message body. In my case removing the buttons gives me ample room to insert the activity indicator.

UIAlertView *WaitPrompt()
  UIAlertView *alert = [[[UIAlertView alloc] 
    initWithTitle:@"Contacting Server\nPlease Wait..." 
    message:nil delegate:nil cancelButtonTitle:nil
    otherButtonTitles: nil] autorelease];
  [alert show];

  UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; = CGPointMake(alert.bounds.size.width / 2, alert.bounds.size.height - 50); [indicator startAnimating]; [alert addSubview:indicator]; [indicator release]; // 250ms pause for the dialog to become active... int n=0; while(n < 250) { [[NSRunLoop currentRunLoop] limitDateForMode:NSDefaultRunLoopMode]; Sleep(1); n++; } return alert; }

We can call the above routine to create our wait dialog, but how do we dismiss the dialog once we have completed our task?

void DismissWaitPrompt(UIAlertView *alert)
	[alert dismissWithClickedButtonIndex:0 animated:YES];

Please pay special attention to the while() loop at the end of the WaitPrompt() function. This section of code executes the main run loop for 250ms which is enough time for the OS to animate the UIAlertView onto the display. If you omit this section of code the chances are the dialog would not display until your processing is complete.

Tags: iPhone UIAlertView Custom programming

Comments (1)

2 Apr 2010 02:37 by Federiko
Thanks man, this really helped, especially the run--loop code :-)


Sites of Interest