Follow @endyourif rss Facebook LinkedIn

ActivityIndicator with a UIWebView ActivityIndicator with a UIWebView

Published on Apr 15, 2009

Because you can never be sure how long it will take to retrieve content from a web page and have it displayed on the iPod/iPhone, it's quite nice to provide the user with an indication that the content is being retrieved.

The following article provides a nice and easy way to start and stop and animation indicator when the content is being retrieved and has been loaded.

The first thing to do is, in our header file create a couple of variables that we can use in our various functions:

@interface SomeController: UIViewController <UIWebViewDelegate> {
UIWebView *webView;
UIActivityIndicatorView *activityIndicator;

In the code above, we create a UIWebView and an UIActivityIndicatorView. Next, in our loadView() function, we allocate the two variables:

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {

CGRect bounds = [ [ UIScreen mainScreen ] applicationFrame ];

activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.view = activityIndicator;

webView = [ [ UIWebView alloc ] initWithFrame:bounds];
webView.delegate = self;

NSURL *url = [ NSURL URLWithString: @"" ];
NSURLRequest *request = [ NSURLRequest requestWithURL:url ];
[ webView loadRequest: request ];

The follow code allocates our activity indicator and sets it as the view. Next we allocate our web view and perform a request.

Now we need to add some more code to start and stop the animation when our request is started and finished, respectively:

- (void)webViewDidStartLoad:(UIWebView *)webView {
[activityIndicator startAnimating];

- (void)webViewDidFinishLoad:(UIWebView *)webView {
[activityIndicator stopAnimating];
self.view = webView;

The following code starts animating the indicator when our request starts. When the request is finished, we stop animating and we set our view to our webView.

That is the basics behind it. You may notice that in this example because we set the activity indicator view to self.view that it is stretched. You will probably wish to go the extra effort to create a UIView, add the activity indicator to that view. Then set self.view to the new view you created instead of just setting self.view to the activity indicator.

I'll leave that for you to try!

Tags: iPhone | UIWebView | UIActivityIndicatorView

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP