Using threads for a JSON request

August 28, 2008    JSON Programming

Make sure you have JSON Framework installed first.

This is a continuation of Post JSON to a webservice

So if you are writting your webservice application and you have to wait a few seconds to make the request and get the response you will notice that your main application gets locked up. This is due to having to wait for the request to complete and nothing else can work till that request is completed.

So here is where we introduce threads. So the idea is this. We will click on a cell and load the view. It will be a blank view and then we will launch a thread to grab the information. Once we have that information the thread will complete and we can load the table.

So we will start off using the following source code. This is code from the UIImageView in a custom cell example.So for here we need to change our PHP JSON endpoint. We want to simulate the wait so we will just toss in a sleep(5); or such. So the endpoint now looks like this

header('Content-type: application/x-json');

$id = (int)$_GET['id'];

$array = array(
        1 => array(
                'id'    => 1,
                'title' => 'Brown Dog',
                'img'   => '',
        2 => array(
                'id'    => 2,
                'title' => 'Black Dog',
                'img'   => '',
        3 => array(
                'id'    => 3,
                'title' => 'Two Dogs',
                'img'   => '',
        4 => array(
                'id'    => 4,
                'title' => 'Girl',
                'img'   => '',


echo json_encode($array[$id]);

So lets change the endpoint in the code now. Open up JSONViewController.m and in the viewDidLoad method change the NSURL line to look like.

NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:@"", self.itemID, nil]];

You can see the file use to be called test-json-get.php, I just made it test-json-get2.php. The new file has our sleep in it. If you click build and go now, you will notice that if you click on a cell to view it you will experience some delay and the UI is in a locked state till the 5 seconds are up. Once the 5 seconds are up the new view is displayed.

So our goal is to first load that new view and then display like a activity indicator in the upper right. Now you might be saying.. why use threads? Just display the indicator before making the JSON call. Well the reason is while we make the request is that the UI is locked and the indicator will stop so we want to do the request in a background thread so our main UI will continue to work.

So the first thing we want to do is move the JSON code from viewDidLoad into a new method. Lets call it getJSON. So here is what that function should look like

- (void)getJSON {
    NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:@"", self.itemID, nil]];

    NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];

    if (jsonData == nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Webservice Down" message:@"The webservice you are accessing is down. Please try again later."  delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
    else {
        self.jsonItem = [jsonData JSONValue]; 

        // setting up the title
        self.jsonLabel.text = [self.jsonItem objectForKey:@"title"];

        // setting up the image now
        self.jsonImage.image = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: [self.jsonItem objectForKey:@"img"]]]];

Your viewDidLoad should now be an empty method. So now lets put the activity indicator in there. So now the function should look like

- (void)viewDidLoad {
    CGRect frame = CGRectMake(0.0, 0.0, 25.0, 25.0);
    UIActivityIndicatorView *loading = [[UIActivityIndicatorView alloc] initWithFrame:frame];
    [loading startAnimating];
    [loading sizeToFit];
    loading.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
                                UIViewAutoresizingFlexibleRightMargin |
                                UIViewAutoresizingFlexibleTopMargin |

    // initing the bar button
    UIBarButtonItem *loadingView = [[UIBarButtonItem alloc] initWithCustomView:loading];
    [loading release]; = self;

    self.navigationItem.rightBarButtonItem = loadingView;

So you can see we are initing a new UIActivityIndicatorView and then creating a new bar button item and using our new indicator view as the bar item’s view. Then we are placing that item in the right hand side of the navigation bar.

So if we click build and go we will get something like this when we click on a cell.

So now we need to do the threading. So our JSON request got moved into a new function so that is where we will do the bulk of the request. So lets set that up.

At the top of the getJSON method you want to put the following code.

NSAutoreleasePool *pool = [ [ NSAutoreleasePool alloc ] init ];

At the bottom of that method you want to put the following

[pool release];

So we are creating an auto release pool. Any items that we are set to autorelease in-between the two lines above won’t be released until we call [pool release]

So now we just need to init the thread. So at the bottom of viewDidLoad method add the following

[NSThread detachNewThreadSelector: @selector(getJSON) toTarget:self withObject:nil];

So that will call the method getJSON in a new thread. Now when you click build and go and click a cell and wait 5 seconds you will see the following.

You will notice that our indicator is still there, so we should remove that. So at the bottom of getJSON we want to remove it once the request is done. So add the following line

self.navigationItem.rightBarButtonItem = nil;

That is all you need for threads. Very simple huh? As always you can grab the code here.

comments powered by Disqus