How to read a remote JSON in iOS

Hi friends, it has been a while since I last post a article here. Because of that, this post going to be a new beginning with new category for my blog. If you have stayed with me from the start, you know that I wrote some blog posts on J2ME, Android as well as BlackBerry 10. Here comes a iOS series :-) 

Just like the past, we directly jump in to the todays’ topic. In this blog post you can learn, check availability of the Internet with your device, making a synchronous request to server, reading a JSON file content and update UI content. First of  all I’ll show you the end result of our application. To be honest, there is nothing at all with the UI. I just display the end result using UILabel.

Figure One

Figure 1

After you complete the application and run it in your device or simulator you will be able to see this UI if your device is not connected to any Internet source. Just like I mentioned earlier, this is our one of the tasks that we are going to learn in this post. To accomplish this task I have used an external library called Reachability library by tonymillion. Let’s jump to code and see it first.

 * This is a class method to check the device is connected to Internet or not.
 * Need this library @link @/link
 * @return BOOL Yes, if device is connected
+ (BOOL)isConnectedToInternet {
    if (debugEnable) NSLog(@"%@ * isConnectedToInternet", TAG);

    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    if (networkStatus == NotReachable) {
        return NO;
    } else {
        return YES;

Above is the relevant code which will use the library and check the device is already connected to Internet source and return the status. The file included above code is ANUNetAvailability.m. Okay… Figure 2 will show you the other screen which you will get after reading the JSON file.

Figure Two

Figure 2

“What nonsense is that”, you will surely think like that😉 Don’t worry. Just visit this link and see the JSON content. Then you will understand, after we successfully reading the remote JSON file, we have extracted song names and display in the UI.

First we need to send the server request to get the JSON content. Here how we do it.

 * Using the string URL, create external server request to gather data
- (void)createSyncRequest {
    if (debugEnable) NSLog(@"%@ * createSyncRequest", TAG);

    // Create URL object using the real world URL string
    NSURL *url = [NSURL URLWithString:[ANUAppConstants jsonUrl]];
    // Creates and returns a URL request for a specified URL with default cache policy and timeout value.
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLResponse *response;
    NSError *error;

    // There are Async and Synchronous requests for URLConnection.
    // Here I've used Synchrounous request because I'm ruiing this process in a separate thread.
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    ANUJsonReader *jsonReader = [ANUJsonReader alloc];
    [jsonReader readJsonStr:responseData];

My old friends know, that my code comments will explain the source code. Therefore I’m not going to repeat it here. This code snippet is in my ANUWebConnect.m source file where you will get the link at the end of this post.

At the moment, we have checked the Internet availability and completed sending synchronous URL request and receiving data from server. Now we are passing those data to a function which will convert those data to readable format and extract the JSON content as we need. Below code is in ANUJsonReader.m

 * Iterate through the received JSON
 * \param paramResponseData Server response data
- (void)readJsonStr:(NSData *)paramResponseData {
    if (debugEnable) NSLog(@"%@ * readJsonStr:", TAG);

    songNamesMutArr = [[NSMutableArray alloc] init];
    NSError *readError;
    // Returns a Foundation object from given JSON data.
    NSDictionary *fullJsonDic = [NSJSONSerialization JSONObjectWithData:paramResponseData options:0 error:&readError];
    NSArray *songArray = [fullJsonDic objectForKey:jsonObjSong];

    // Loop through the JSON array to collect song names
    for (int i=0; i<songArray.count; i++) {
        NSDictionary *songElementDic = [songArray objectAtIndex:i];
        NSString *songName = [songElementDic objectForKey:jsonObjSongName];
        [songNamesMutArr addObject:songName];
    NSArray *songsArray = [NSArray arrayWithArray:songNamesMutArr];
    NSDictionary *userInfoDic = @{songsArrKey: songsArray};

    // After completing the data, notify to all subscribers
    [[NSNotificationCenter defaultCenter] postNotificationName:dataReadyNotifyStr object:nil userInfo:userInfoDic];

Now you have put song names in to an NSArray and also you are notifying to any observer who is subscribed to receive notification about data ready message. Till this process complete you will be seen just a UILabel in your screen with the context of ‘Label’. Some people may not be able to seen that for a long time, because you received the server response quickly and the UI will update immediately. 

As good programmers, we are not going to put time consuming activities in the main thread. We detach them from the main thread like below.

// Detach sending server request from the main UI thread
[NSThread detachNewThreadSelector:@selector(createSyncRequest) toTarget:webConnect withObject:nil];

Because of above reason UI thread is not control in our hand by the time we extracted JSON song names. That is why we need a subscriber to listen, when the data is ready to display.

// Adds an entry to notification receiver’s dispatch
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSongs:) name:dataReadyNotifyStr object:nil];

Even that is not enough to update the main thread UILabel. To do that we need below code.

// Update the main UI
    dispatch_async(dispatch_get_main_queue(), ^{
        _placeholderLabel.text = [NSString stringWithFormat:@"%@", receivedSongsArr];

All those code snippets are in ANUViewController.m.

So I think that is it for todays’ post. Did I forget something😉 No… this is the link to GitHub repo to download full source codes related to this post. You will be able to download the relevant source codes only but not the whole project. Because I think it is always better to dirt your own hands with writing codes🙂

Hope to see you soon next time.








About AnujAroshA

An undergraduate in the stream of ICT (Information & Communication Technology). A simple person :)
This entry was posted in iOS and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s