ActivityIndicator with a UIWebView

A

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:

[code]@interface SomeController: UIViewController <UIWebViewDelegate> {
 UIWebView *webView;
 UIActivityIndicatorView *activityIndicator;
}
[/code]

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

[code]// 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: @”https://www.endyourif.com” ];
 NSURLRequest *request = [ NSURLRequest requestWithURL:url ];
 [ webView loadRequest: request ];
}
[/code]

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:

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

– (void)webViewDidFinishLoad:(UIWebView *)webView {
 [activityIndicator stopAnimating];
 self.view = webView;
}
[/code]

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!

Other useful articles

About the author

By Jamie

My Books