Write a post

iOS QuickTip: Getting and Reading JSON Data from a URL

Published Jan 06, 2016Last updated Feb 22, 2017
iOS QuickTip: Getting and Reading JSON Data from a URL

Why

In every single one of the iOS apps I've created, I have had to call a server URL - either my own or 3rd party to get some data. There's an infinite number of reasons to be doing this for example: logging a user in, getting updates, checking for high scores, creating and saving a new customer to your database, etc...

This may seem like a daunting task and after searching around, I found most people have over complicated this issue. So here is a little trick only using a few lines of code!

Setup JSON

Now before we go any further we are going to create some test JSON data. Let's pretend we wanted to get the high scores for our new game. Since we don't have a database setup to actually get the data we will just create some to test with.

Copy/Paste the below into a new file and save is as high_scores.json

[{
  "firstName": "John",
  "score": "302"
}, {
  "firstName": "Anna",
  "score": "288"
}, {
  "firstName": "Peter",
  "score": "243"
}]

OK so now we have our test data, you'll want to upload it to your server so we can call it via the URL for example (www.YourWebSite.com/high_scores.json).

Retrieving and Reading the JSON via Objective-C

Now you'll want to head back into your iOS project since this is where you want to get this data.

From here Copy/Paste this code to call your URL and get the high scores

NSError *error;
NSString *url_string = [NSString stringWithFormat: @"http://YourWebSite.com/high_score.json"];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"json: %@", json);

The only line you need to change here is the second line with the URL, replace "http://YourWebSite.com/high_score.json" with your own website.

Now when you run your app and this code you should see the high scores in xcodes console. Just like this:
enter image description here

Nice! You have successfully called data from your server directly into your iOS app!

If you need to send POST data to your PHP server checkout the code here.

Contact me if you have any questions!

Discover and read more posts from Rob Heller
get started
Enjoy this post?

Leave a like and comment for Rob

Learn a New Language: Migrating from JavaScript to PHP
5 Great Resources to Learn Laravel Development
Turbocharge Your iOS Development: Cocoapods, fastlane, and Xcode Tutorial