UIActivityIndicatorView in UINavigationBar

Here’s a short snippet I find myself using often when I have to communicate with web services: Adding an UIActivityIndicatorView to the bar of an UINavigationController, so that users are informed of the ongoing process in the background. Unfortunately you can’t plug this together in Interface Builder, so we have to do it in code.

- (void)viewDidLoad {
   [super viewDidLoad];
   // Add an activity indicator to the navigation bar
   UIBarButtonItem *activityItem = [[UIBarButtonItem alloc] initWithCustomView:activityView];
   self.navigationItem.rightBarButtonItem = activityItem;
   [activityItem release];

This requires the activityView to be defined as a property of the view controller and setup in Interface Builder (hidden when stopped).

IBOutlet UIActivityIndicatorView *activityView;

When the communication with the web service start you can simply call

[activityView startAnimating];