iOS

How To Fetch and Parse JSON Using iOS SDK


Editor’s Note: This week, Ziad Tamim will show you how to fetch and parse JSON. In this tutorial, we will be focusing on adding JSON support to your iOS apps by demonstrating how to create a simple app using Meetup API. The tutorial may be a bit complicated than other tutorials we covered before. You’re expected to have basic knowledge of JSON and design patterns.

Enter the JSON programming tutorial.

First, what’s JSON? JSON (short for JavaScript Object Notation) is a text-based, lightweight and easy way for storing and exchanging data. It’s commonly used for representing structural data and data interchange in client-server applications, serving as an alternative to XML. A lot of the services we use everyday have JSON-based APIs. Most of the iOS apps including Twitter, Facebook and Flick send data to their backend web services in JSON format.

json intro tutorial

As an example, a JSON representation of a Movie object may look like this

As you can see, the JSON data is human-readable and easier to parse than XML. If you still have no idea about JSON, check out JSON Guide to learn more about it.

Since the release of iOS 5, the iOS SDK makes it easy to fetch and parse JSON data. In this tutorial, we’ll demonstrate how to use the built-in API to query a JSON-based API from Meetup and deal with the returned data appropriately.

Take a Look at Our App

Before we move onto the code, let’s take a look at what we’ll build.

In this tutorial, we’ll create a simple app called BrowseMeetup that consumes Meetup’s public API. If you haven’t heard of Meetup, it is the world’s largest network of local groups. You’re free to use Meetup to organize a local group or find one of the thousands already meeting up face-to-face. Like other social networks, it provides open API for accessing its data from your own apps.

The BrowseMeetup app will consume the web service of Meetup to look up for groups nearby. The app will get the current location and then automatically load the nearby Meetup groups.

BrowseMeetup Demo App

Note: This app utilizes Core Location framework. If you don’t have any idea about it, check out our tutorial about How To Get the User Location in iPhone App.

Getting Started

It’s time to set up the project to manage the BrowseMeetup application. Launch Xcode and create a new project based on the Master-Detail Application iOS app template. In the project options, you’ll need to check the Storyboard and Automatic Reference Counting boxes. This app will provide only iPhone Views, so choose iPhone for the device family and save the project. Delete the DetailsViewController and in the storyboard, design the user interface similar to the one below:

BrowseMeetup Storyboard

Storyboards of BrowseMeetup App

The focus of this tutorial is on JSON fetching and parsing. So to save your time from setting up the project, you can download this project template to start with. The template already pre-built the user interface and implemented the Core Location for you.

Tip: If you have no idea about table view and wonder how the navigation bar works, check out our tutorials in the free iOS course.

Working with Meetup APIs

Before you can use Meetup APIs, first create a new account on Meetup. Start by creating a new account by going to APIs Doc and clicking on the button “Request to join this Meetup group”, then fill the necessary information and hit “Sign Up”, then go step by step until its done.

Screen Shot 2013-08-26 at 10.06.27 PM

We’ll use one of the Meetup APIs (i.e. https://api.meetup.com/2/groups) for fetching the Meetup groups held at a certain location. The call allows developers to specify the location by using latitude and longitude. You can test the call by using the API console.

Here is a sample JSON response for this request (https://api.meetup.com/2/groups?&sign=true&lat=51.509980&lon=-0.133700&page=1):

Application Design and How It Works

As mentioned, Meetup API provides a method for requesting groups in a certain location. The response data will be sent in JSON format. We’ll need an object that can retrieve the data and construct our domain object from the encoded data. Below is an overview of the application design showing how the classes are structured and how they work together to get the meetup groups:

BrowseMeetup - Design Overview

BrowseMeetup – Design Overview

It may be a bit complicated for some of you. But let me give you a brief walkthrough. We create a MeetupManager, in which it will request for Meetup groups for a particular location. Here the MeetupManager acts as a facade. If you haven’t heard of the Facade design pattern, you can think of it as a coordinator of other classes. The Facade tries to provide a simplified interface for the view controller and shields it from the underlying implementation.

The MeetupCommunicator class is used for communicating with the Meetup API. Once Meetup responds with the JSON-formatted response, we’ll pass it to GroupBuilder that constructs the Group object.

The MasterViewController uses Core Location to figure out the current location and informs the MeetupManager to get the Meetup groups for that location. The MeetupManager coordinates with other classes to retrieve the groups. Once the groups are retrieved, it communicates with the MasterViewController via the delegate and pass the groups found. The MasterViewController then presents the groups in the table view.

Creating JSON Data Model

We are going to start by implementing the model layer. The Group class represents the group information in the BrowseMeetup app and is used to store the group information returned by Meetup. Here is a sample JSON response of a Group object:

The above JSON response represents a single Meetup Group. We’ll not use all the group data returned. But simply use the “name”, “description”, “who”, “country” and “city” fields. These fields are just good enough for presenting in the table view of our app. Now create a new file using the Objective-C class template. Name it Group, make it a subclass of NSObject and add the following code in the header file:

These properties are the information that we will use in our app to achieve the final result depicted earlier.

Fetching JSON Data Using Meetup API

First create a new file using Objective-C protocol template and name it as MeetupCommunicatorDelegate. Fill it with the below code:

The MeetupCommunicator class is responsible for the communication with the Meetup APIs and fetching the JSON data. It relies on the delegate of MeetupCommunicatorDelegate to handle the parsing of JSON data. The communicator has no idea how the JSON data is handled. Its focus is only on creating connection to the Meetup APIs and fetching the raw JSON result.

With the delegate created, create another class file and name it as MeetupCommunicator. Open the header file and put in the below code:

We are creating a property to keep track of the communicator delegate, then defining a method for searching Meetup groups in a certain location. Next, open the MeetupCommunicator.m and place the code below:

The Meetup API needs a key to work. If you’re registered an account, you need to get one by going to API Key page. Simply click on the lock icon beside the textfield to reveal the key. Copy the text inside it and replace the value of the macro API_KEY with your own API key.

As mentioned in the earlier section, we use the following Meetup API for searching group in a specific location. The API accepts the location in the form of latitude and longitude. Here is a sample Meetup URL to connect:

In the implementation of the method, we first construct the Meetup API URL with the specified latitude, longitude, the number of groups and the API key. In order not to blocking the UI, we load the data for a URL request asynchronously by using the “sendAsynchronousRequest:” method of NSURLConnection. Finally, when the JSON data is retrieved, it passes the data to the delegate for further processing.

Parsing JSON Data and Building Group Objects

When MeetupManager receives the data in JSON format, we use the class method of GroupBuilder to convert the data into Group objects. Create a new file with Objective-C class template and name it as GroupBuilder. Open the header file and paste the following code:

Next, open “GroupBuilder.m” and implement the method with the following code:

The “groupsFromJSON:” method is designed to convert raw JSON data into an array of Group objects. Since the release of iOS 5, the iOS SDK comes with a class called NSJSONSerialization for parsing JSON data. Developers can use the class to convert JSON to Foundation objects or convert Foundation objects back to JSON.

When reading JSON data using NSJSONSerialization, all the keyed lists are automatically turned into NSDictionary objects. For array, it’s converted into NSArray instances. Any strings encountered along with the names of named items in keyed lists are converted into NSString, while purely numeric strings are converted into NSNumber objects. Lastly, any values of null are represented using NSNull.

Referring the sample response we showed you in earlier section, the Meetup API returns a JSON response with two main parts – results and meta. We’ll just need the “results” part. The code is very straightforward. We loop through the results and look into each NSDictionary inside it. We then create a Group object and fill it with the necessary information, then adding it to the mutable array.

Putting the Pieces Together with MeetupManager

Now you should know how to work with JSON, parse the data and convert it into objects. Next, we’ll implement the MeetupManager which serves as a coordinator of the underlying classes.

First, create a new file with the Objective-C protocol template and name it as MeetupManagerDelegate. Add the code below in the MeetupManagerDelegate.h:

This delegate declares two methods and will be called by MeetupManager when the groups become available. The first method is called when the list of groups retrieved from Meetup is parsed, while the second method is invoked when an error occurred. The MeetupManagerDelegate will be implemented by MasterViewController that we’ll discuss in later section.

Next, create a new file with the Objective-C class template and name it MeetupManager. Then open the header file and add the code below:

As said, the MeetupManager acts as a façade. The app’s controller can work with the model object (i.e. Group) created without knowing any details about the network connection, JSON fetching/parsing or how the group objects are created. What the controller just needs to know is to use the “fetchGroupsAtCoordinate:” method for fetching Meetup groups.

We set up a property to keep an instance of our communicator which we will cover later and the other to keep track of the MeetupManagerDelegate. The “fetchGroupsAtCoordinate:” method will be used by the controller to fetch groups.

Next, open MeetupManager.m and place this code:

Here we implement the method fetchGroupsAtCoordinate:coordinate to fetch the groups in a certain area using the searchGroupsAtCoordinate:coordinate method of the communicator. We also implement the methods of MeetupCommunicatorDelegate for handling the JSON-formatted results as retrieved by the communicator.

The code inside the first method of the protocol receivedGroupsJSON:objectNotation uses the class method of GroupBuilder to convert the JSON result into Group objects and then informs its delegate with the Group objects. If there is any problem while processing the request, we invoke the other method (i.e. fetchingGroupsFailedWithError:) of the delegate to notify the controller that a problem is occurred.

Displaying the List of Groups

The first thing to do is hooking all these classes together so the MeetupManager can work. Open the MasterViewController.m, import the required header files, update the interface and declare the MeetupManager instance as follows:

Later we’ll implement the methods as defined in MeetupManagerDelegate. But first let us instantiate the MeetupManager in the method of viewDidLoad:

We are instantiating a new manager, then fill its communicator property with an new instance, and finally making the current view controller to keep track of any changes. The observer here captures the response of the user when the alert shows up to enable location services to call the method startFetchingGroups: to start fetching groups from server.

Next, open the “MasterViewController.m” and put the below to start fetching:

As the view controller should conform to the MeetupManagerDelegate protocol. Implement the methods as follows:

The “didReceiveGroups:” method will be called when the Meetup groups is grabbed from the Meetup server with an array instance returned. Here we simply reload the table view to display the new data.

Lastly, set up the methods of the table view by pasting the code below:

The above code is very straightforward. We retrieve the groups from the array and fill the table cell with the group information.

Compile and Run

Now it’s time to test the app. Compile and run it in the Simulator (or a real iOS device if you’ve registered the iOS developer program). Setup the location of the Simulator to London, UK. You should get the Meetup groups similar to the below screenshot:

BrowseMeetup London
Tip: If you have no idea about testing location in iPhone Simulator, check out the Core Location tutorial.

Summary

We have covered in this tutorial many aspects of programming by adopting the right design pattern to work with JSON data. You should now have a hands-on experience on fetching and parsing JSON data.

The tutorial may be a bit difficult if you’re new to design pattern. However, this shouldn’t scare you away from using JSON in your app. The iOS SDK makes it so easy for your apps to work with JSON. In summary, you simply create a URL connection, fetch the JSON data and parse it by using the built-in NSJSONSerialization class.

You can find various free APIs (such as Kiva and TMDb) on the Internet. As an exercise, try to pick another API and develop another app for it. Say, you can develop a simple app and display a list of the most recent fundraising loans using Kiva API.

For your complete reference, you can download the full source code of the Xcode project here.

As always, please leave us comment and share your thought about the tutorial.

iOS
Customize Table View Cells for UITableView
Tutorial
Building a Trello-like iOS App with Drag & Drop API
iOS
How to Use SQLite to Manage Data in iOS Apps
  • Osvaldo Cipriano

    Nice tutorial, again 🙂


  • vikram

    vikramvikram

    Author Reply

    Nice tutorial with very good example…Thanx allot


  • Steve

    SteveSteve

    Author Reply

    Nice tutorial!
    It works well, but rendering tableView takes so long.
    Is there any way to make rendering table view faster?


    • Ziad Tamim

      Ziad TamimZiad Tamim

      Author Reply

      You can add a spinner to table view while data is loading, this way the user knows some work is going on.


  • Paulo

    PauloPaulo

    Author Reply

    Nice tutorial! Tks a Lot 😉


  • LittlePeculiar

    Very nice tutorial. I love to come here and learn new stuff and more importantly, your clear and efficient design patterns.
    Thanks.


  • frenzen

    frenzenfrenzen

    Author Reply

    ive been looking on every single site for so long for a good json tutorial and i refresh and see this awesome stuff


  • Thiodor

    ThiodorThiodor

    Author Reply

    One thing: the data is loaded but it is not displayed on the table view until you scroll it. Any ideas how to fix it or on which part of the code you must put [tableview reloadData].
    Thanks.


    • Juan Carlos Orrego

      This worked for me:

      dispatch_async(dispatch_get_main_queue(), ^{
      [self.tableView reloadData];
      });

      Based on the example, this should go in didReceiveGroups method of the master controller.


      • Daan

        DaanDaan

        Author Reply

        Exactly what I needed ! Table redraw seemed to take forever…


  • ДЕНИС

    ДЕНИСДЕНИС

    Author Reply

    РАСИЯ ДЛЯ РУСКИХ!!


    • Name

      NameName

      Author Reply

      москва для москвичей!


  • Ly4S

    Ly4SLy4S

    Author Reply

    Thanks a lot for a great tutorial! I actually didn’t follow verbatim…I just needed to get the concept of how to interact with JSON APIs, so I could apply it to my own app, and this tutorial was a massive help. Can’t thank you enough for how easy you made the process for me. Keep up the great work you are doing!


  • Jordan

    JordanJordan

    Author Reply

    Obviously an app like this won’t work without the internet. Is there an easy way to display to the user that “hey, you need a network connection to run this app”? Thanks for a great tutorial!


  • Arthur_Camara

    Thanks very, very much! Everything I found regarding iOS and JSON was related to old, non-native libraries. This is the best one I could find using native code!


  • Chuck Kelly

    ridiculously overly complicated for the objective of the tutorial…..can you ppl not just create a simple json parsing tutorial thats uses afnetworking and a tableview like everyone on the damn internet wants or is there some damn conspiracy on the internet amongst developers making actually relevant and practical tuts to protect their salary’s?


    • Aaron Wolverton

      Haha, this is mean, but I would have to agree.


    • cerberusss

      cerberussscerberusss

      Author Reply

      I found the described class hierarchy very useful to structure my app.

      Maybe it was overly complicated for you personally?


    • TooEasy

      TooEasyTooEasy

      Author Reply

      Ridiculously complicated is an understatement


  • shane film

    shane filmshane film

    Author Reply

    Please provide code to modify the groupsFromJSon method within the GroupBuilder class access other data that like photo_link, or short name. Can you explain how to parse this data that is more deeply nested within the results dictionary? It appears that a great deal of the keyValues are part of NSArrays with data that isn’t accessible at the top level of results. This is is a phenomenal tutorial. Keep up the great work.


    • shane film

      shane filmshane film

      Author Reply

      Actually, I solved this by adding an NSArray to the Group.h file and then referenced it in the tableView of MasterViewController.m using valueForKey. Example: [group.category valueForKey:@”shortname”]). This returns the shortname of the category that is an NSArray that was added to the Group object.


  • Aaron Wolverton

    Is this tutorial supposed to display the detail/2nd view when you click on a meetup? It starts out with a master/detail application template, but my project doesn’t present a detail page when you click on a meetup/table cell from the root view.


  • NissiVM

    NissiVMNissiVM

    Author Reply

    How the methods declared in MeetupCommunicatorDelegate can be called in the MeetupManager class if this class is not declared as the delegate of the class MeetupCommunicator?


  • NissiVM

    NissiVMNissiVM

    Author Reply

    Thank you very much for this tutorial, I’ve learned a lot from it! =]


  • lyao

    lyaolyao

    Author Reply

    Really need another try to read this tutorial.


  • Gordon Chan

    Well I like this tutorial very much. I don’t think it is ridiculously overly complicated, instead, I am very much value on the concept of Communicator / Manager / Delegate. As it is a way to have good design of application.

    I am not good at application design and I start learning something like this, using Manager class to manage and work with custom built delegate. I look forward to see if you can provide another extend of this tutorial to show: when there is not only a single view controller, and different type of API call is performed in different view controller, do we still use single Manager class? or call the same Manager in different View controller?


  • Marc

    MarcMarc

    Author Reply

    Thanks, Great Tuts. I like the clarity of delivery on Delegation and MVC


  • Maciek of Ozz

    Unnecessary overcomplicated, but useful 🙂


  • ttotto

    ttottottotto

    Author Reply

    If there are many viewcontrollers to communicate Meetup, all of them should have meetup manager variables? Moreover all of them should be delegate of meetup manager?


  • yassine

    yassineyassine

    Author Reply

    Hi,

    thanks for this tutorial, I have a question, can I work with this tutorial under Xcode 5 and iOS 7 ?!


    • SomeGuy

      SomeGuySomeGuy

      Author Reply

      Yes, this works with Xcode 5 and iOS 7. I have followed the tutorial successfully.


  • TooEasy

    TooEasyTooEasy

    Author Reply

    What’s with the parameter type (NSData*)? I see it gets passed around but what is it exactly? The object “objectNotation” is an NSData type, where does the “objectNotation” parameter get set?


  • clau

    clauclau

    Author Reply

    Hi! i have been tryin to get this to work all day but the selector on the NSNotificationCenter
    is not being called 🙁


  • Brian Fritch

    Like Chuck Kelly I thought AT FIRST that this approach was overly complicated. After I tried a simpler tutorial that didn’t work, I came back, adapted my app to this approach and it worked Perfectly!!

    Most of the tutorials only give part of the information you really need, or are so simple, it’s hard to expand the concept into a practical implementation. This is one of the few sets of tutorials that are actually well written and provide useful, real-world-like examples. Thank you!


  • Calin

    CalinCalin

    Author Reply

    I might have missed it, but aren’t you supposed to tell MeetupCommunicator, that MeetupManager implements MeetupCommunicatorDelegate?

    I mean, how does [self.delegate receivedGroupsJSON:data]; in MeetupCommunicator know to call (void)receivedGroupsJSON:(NSData *)objectNotation in Meetupmanager?

    There should be something like self.communicator.delegate = self; somewhere in MeetupManager implementation, right?

    Thanks for the tutorial 🙂


  • Vishwa Iyer

    This was a very great tutorial, and I learned a lot from it. I just have one question though, is it possible to parse multiple apis using the same code above. If so, how is it possible?


  • surya appkey

    I tried adding 1 page view controller between navigation controler and table view. but after that the list does not display data from a web service. can anyone help me?


  • byakuya

    byakuyabyakuya

    Author Reply

    Hi guys,

    I have been following many of your tutorials and I am totally fond of your work. Thanx a lot for what you are doing, it helps me a lot. I would like to perform this tutorial but for me the meetup API doesn’t work. Even if I am connected to meetup, when I try your request with my browser I have the following response from the server : {“details”:”API requests must be key-signed, oauth-signed, or accompanied by a key: http://www.meetup.com/meetup_api/docs/#authentication“,”problem”:”You are not authorized to make that request”,”code”:”not_authorized”}

    Can you help me please? Your tutorial is nearly exactly what I need to do for my own app, so it would help me a lot to perform the entire tutorial.

    Regards


  • Alexandre Carmo

    Hello.
    Good tutorial.
    I have a problem using iOS 8, when I use iOS 7.1, this tutorial execute ok, I used emulator iOS 7.1 and device (iPhone 5s) using iOS 7.1, but when I use iOS 8 (emulator or device), dont display anything. There is not error message, and the json don’t return lines. What’s changed in iOS 8? Maybe localization ?


  • Alexandre Carmo

    Hello.
    Good tutorial.
    I have a problem using iOS 8, when I use iOS 7.1, this tutorial execute ok, I used emulator iOS 7.1 and device (iPhone 5s) using iOS 7.1, but when I use iOS 8 (emulator or device), dont display anything. There is not error message, and the json don’t return lines. What’s changed in iOS 8? Maybe localization ?


  • Eric

    EricEric

    Author Reply

    Great tutorial. I got it working for everything except the description property. Xcode says auto synthesis won’t work for read/write so makes it read only. This causes crashes when I try adding the JSON data for description. Any suggestions?


  • James

    JamesJames

    Author Reply

    Excellent tutorial. How would you use this design pattern with multiple API calls from different ViewControllers? Thanks


  • Random Act Of Code

    For those trying to run this, there are two fixes that need to be applied after downloading the project:

    Group.m
    @implementation should look like this:
    @implementation Group
    @synthesize description=_description;

    @end

    The reason: ‘description’ is a property of NSObject. Not fully synthesizing it results in an exception.

    AppDelegate.m
    Replace -(void)locationManager:… with this:
    – (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
    {
    if (status == kCLAuthorizationStatusAuthorized) {
    NSLog(@”a location services request has been made”);
    [[NSNotificationCenter defaultCenter] postNotificationName:@”kCLAuthorizationStatusAuthorized” object:self];
    }else{
    NSLog(@”Unauthorized attempt to use location services.”);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Access to Location Services Denied”
    message:@”To re-enable, please go to Settings and turn on Location Service for this app.”
    delegate:nil
    cancelButtonTitle:@”OK”
    otherButtonTitles:nil];
    [alert show];
    }

    }

    This provides a hint to the user as to why they’re staring at a blank screen. If you’re running this on the simulator, go Home, then Settings, then Privacy, Location, BrowserMeetup and select ‘Always.’ Check that Location Services is also enabled.

    You’ll have to enable Location Services access each time you build.


  • Nick Enchev

    Couldn’t you just show us how to serialize/deserialize JSON? Why create an entire app with a bunch of other important concepts that are completely unrelated to your post?


  • Nitin

    NitinNitin

    Author Reply

    How to use oauth for any services in ios ?


  • Nitin Nikam

    wo ho… nice tut


  • Steven Tan

    Steven TanSteven Tan

    Author Reply

    can you do this tutorial with swift language ?


  • Sasi Kumar

    Sasi KumarSasi Kumar

    Author Reply

    -(void)JSON_GET_CONNECTION1:(NSString *)URL

    {

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];

    NSData *theData = [NSURLConnection sendSynchronousRequest:request

    returningResponse:nil

    error:nil];

    dataDictionary = [NSJSONSerialization JSONObjectWithData:theData

    options:0

    error:nil];

    NSLog(@”dataDictionary1:%@”,dataDictionary);

    NSLog(@”CityName %@”,[[dataDictionary objectForKey:@”doctor_data”] valueForKey :@”cit_name”]);

    }


  • TheUnreal

    TheUnrealTheUnreal

    Author Reply

    The app shows an empty table, even after downloaded the full souorce |:


  • Random Act Of Code

    How to get this to run since iOS 8 – it looks long to show the various problems, where to find them and how to solve them, but really there are MINOR changes to the base code:

    1. Download the project

    2. Run BrowseMeetup.xcodeproj

    3. Warning: “BrowseMeeting” is a project downloaded from the internet. Are you sure you want to open it? Open.

    4. 27 Warnings exist at this point. Go to the Warnings and select the first one – Validate Project Settings – Update to recommended settings – then Perform Changes/Continue.

    5. 26 Warnings exist. These are related to source control; All the files need to be committed and then a Refresh Status run. This can be done later. For now, leave it.

    6. Run the app: Blank Browse Meetup table. Not good.

    7. Stop the app, 29 Warnings now.

    8. Warning: Format String Issue – The suggestion is to replace %d with $lu in GroupBuilder.m:

    Before: NSLog(@”Count %d”, results.count);

    After: NSLog(@”Count %lu”, (unsigned long)results.count);

    9. Warning: Auto property synthesis will not synthesis property ‘description’… In Group.m:

    Add: @synthesize description=_description;

    after @implementation Group

    10. Warning: ‘kCLAuthorizationStatusAuthorized’ is deprecated… AppDelegate.m:

    Before: if (status == kCLAuthorizationStatusAuthorized) {

    [[NSNotificationCenter defaultCenter] postNotificationName:@”kCLAuthorizationStatusAuthorized” object:self];

    }

    After: if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways) {

    [[NSNotificationCenter defaultCenter] postNotificationName:@”kCLAuthorizationStatusAuthorized” object:self];

    }

    NOTE: In postNotificationName:@”kCLAuthorizationStatusAuthorized”, @”kCLAuthorizationStatusAuthorized”, is a message. That is, you can put ANYTHING there – it is not bound to the deprecated status or part of the Objective C language, but is a string that is broadcast to the rest of the application. If you change it here, you will need to change it anywhere your app is listening for it. In this case, MasterViewController.m, viewDidLoad:

    [[NSNotificationCenter defaultCenter] addObserver:self

    selector:@selector(startFetchingGroups:)

    name:@”kCLAuthorizationStatusAuthorized”

    object:nil];

    11. Run the app: Same results. Stop the app. Now back to 26 Warnings. Better.

    12. iOS 8 introduced a change to kCLAuthorizationStatusAuthorized. kCLAuthorizationStatusAuthorized became kCLAuthorizationStatusAuthorizedAlways and kCLAuthorizationStatusAuthorizedWhenInUse. As such, in Settings/Privacy/Location Services, you will need to first make the setting be ‘Never’ (because there is no other choice), then go back and change it to Always or While Using The App.

    13. Run the app: You get data! But, the app isn’t really working 100%. Take a look…

    14. Stop the app, go back to Settings/Privacy/Location Services – your settings for BrowseMeetup have been wiped out, or will be if you try to run the app again. This is terrible!

    15. iOS 8 introduced the ability to ask a user if they wanted to enable Location Services – in MasterViewController, viewDidLoad,, add this before the end of the closing bracket:

    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {

    [self.locationManager requestAlwaysAuthorization];

    }

    16. Run the app… blank table… but now this warning in the console – stop the app:

    BrowseMeetup[23993:4593295] This app has attempted to access privacy-sensitive data without a usage description. The app’s Info.plist must contain an NSLocationAlwaysUsageDescription key with a string value explaining to the user how the app uses this data

    17. In Supporting Files, BrowseMeetup-Info.plist:

    Move your mouse pointer over Information Property List – click the ‘+’ – select Privacy – Location Always Usage Description – then type in a Value (something like ‘Always Description’ for now, something more robust later)

    Move your mouse pointer over Information Property List – click the ‘+’ – select Privacy – Location When In Use Usage Description – then type in a Value (something like ‘When In Use Description’ for now, something more robust later)

    You will see the Value you entered in the next step… (look for ‘Always Description’)

    18. Run the app… Popup – Allow “BrowseMeetup” to access your location even when you are not using the app? Always Description Click Allow – blank screen, but if you drag the table cells, you’ll see it populates. Stop the app.

    19. Go back to Settings/Privacy/Location Services and change the setting for BrowseMeetup, then go back to the app, then exit the app – the settings stayed. Very good.

    20. Fix the blank table problem: MasterViewController.m, didReceiveGroups – make the following change:

    Before: [self.tableView reloadData];

    After: dispatch_async(dispatch_get_main_queue(), ^{

    [self.tableView reloadData];

    });


    • Random Act Of Code

      In MasterViewController.m, replace the existing didReceiveGroups with the following so that the table will display data immediately upon receiving it; otherwise, the user would have to swipe the table or wait a little longer for the table to (eventually) show anything:

      – (void)didReceiveGroups:(NSArray *)groups

      {

      _groups = groups;

      dispatch_async(dispatch_get_main_queue(), ^{

      [self.tableView reloadData];

      });

      }


  • Varun

    VarunVarun

    Author Reply

    I tried downloading the code and compiled it but shows blank screens that’s it
    also what i observed is people praising this article have pic on their profile while others don’t
    Can someone really help me find a simple implementation of json api int list in my ios app


  • Varun

    VarunVarun

    Author Reply

    Also,
    I downloaded the files and complied it. Shows blank rows


  • JanBask Training

    Easily we can fetch Jason using iOS SDK, very informative tutorial. Thanks for sharing with us.


  • Prak Borin

    Prak BorinPrak Borin

    Author Reply

    your link to download was removed..


  • Deepin Do

    Deepin DoDeepin Do

    Author Reply

    The link to download was not working


  • andlearning

    Thank you for sharing the great article for me to learn ios programming language.


Shares