Monday, February 7, 2011

Objective C: Use Network Activity Indicator in iPhone Apps with GTMHTTPFetcher

The Google Toolbox HTTP Fetcher (GTMHTTPFetcher) allows you to send synchronous and asynchronous HTTP request in iPhone/iPad Apps using Objective C/Xcode.

Pretty common in those Apps is to display the network activity indicator during the request process.

The below instructions should also work for other HTTP libraries, you just need to replace the observer names accordingly.

This is how you can do it. The example tutorial below shows how to add this functionality to the RootViewController, but it could be added to any ViewController.

In the RootViewController.h

// RootViewController.h

#import <UIKit/UIKit.h>

@class GTMHTTPFetcher;

@interface RootViewController : UIViewController <UINavigationControllerDelegate> {

 int networkActivityCounter;

- (void)startFetchingData;
- (void)fetchData:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)retrievedData error:(NSError *)error;


Important here is the networkActivityCounter that will later hold the number of requests that are currently running.

In the RootViewController.m

// RootViewController.m

- (void)viewDidLoad{
 //add observer for fetcher start and stop events
 NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
 [nc addObserver:self selector:@selector(incrementNetworkActivity:) name:kGTMHTTPFetcherStartedNotification object:nil];
 [nc addObserver:self selector:@selector(decrementNetworkActivity:) name:kGTMHTTPFetcherStoppedNotification object:nil];

First add the observers for the fetch start and stop events in the viewDidLoad method.

#pragma mark Network activity

- (void)incrementNetworkActivity:(NSNotification *)notify {
  if (1 == networkActivityCounter) {
    UIApplication *app = [UIApplication sharedApplication];
    [app setNetworkActivityIndicatorVisible:YES];

- (void)decrementNetworkActivity:(NSNotification *)notify {
  if (0 == networkActivityCounter) {
    UIApplication *app = [UIApplication sharedApplication];
    [app setNetworkActivityIndicatorVisible:NO];

The increaseNetworkActivity is called when a fetch requested started, when the counter is at 1 the indicator gets displayed. After when the counter gets increased it doesn't need to be activated anymore, its still running.

Each time a fetch request has stopped the activity gets decreased, at 0 activity the indicator gets invisible.

- (void)dealloc {
 //remove the observer
 NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
 [nc removeObserver:self];
 [super dealloc];

Don't forget to remove the observer when not needed anymore.


Post a Comment