Write a post

Enjoy this post? Give Rob Heller a like if it's helpful.

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

13Replies
Varun Jain
6 months ago

What’s next ?
How do i take this data from json to listview or individual array for firstname and score

Robbie Heller
6 months ago

You can access the data the same way as any array.

If you wanted to get the first name you could do:

[json getObjectAtIndex:0] getObjectForKey:@“firstName”]

Varun Jain
6 months ago

I used
NSLog(@“Item: %@”,json[0][‘firstName’]);
this gives
Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[__NSDictionaryI objectAtIndexedSubscript:]: unrecognized selector sent to instance 0x60800007e080’

Robbie Heller
6 months ago

try doing it the objective-c way

NSLog(@“Item: %@”, [json getObjectAtIndex:0] getObjectForKey:@“firstName”] );

Varun Jain
5 months ago

Done. Thanks a Ton. :)
Now, Can you please also help me to understand What do I need to change in order to get data from a post API instead of get ?

Robbie Heller
5 months ago

I created a new post with the code for you
https://www.codementor.io/r…

bhavani
7 months ago

Hello.
How to get url from the Json link to get the images?

Robbie Heller
6 months ago

What do you mean? Could you some code? You can access data in the array like this.

If you wanted to get the first name you could do:

[json getObjectAtIndex:0] getObjectForKey:@“firstName”];

bhavani
6 months ago

for parsing JSON using obj c. I wrote the code like this

-(void)viewDidAppear:(BOOL)animated{

[[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:@“http://whatsinthestreet.com…”] completionHandler:^(NSData * _Nullable data ,NSURLResponse * _Nullable response,NSError * _Nullable error){

NSLog(@“response %@”,response);

NSLog(@“data %@”,data);

NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

NSLog(@“dict%@”,dict);

NSArray *array;

array=[dict valueForKey:@“data”];

NSLog(@"%@",array);

for(id obj in array)

{

NSString *urlStr=[obj objectForKey:@“img”];

_myImg.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: urlStr]]];

NSLog(@“urlStr%@”,urlStr);

}

}]resume];

}

I’m only getting the final image among four images, how could I get auto scrollview of all these images.Please help me , I’m new to this language

Mickael Domingues
9 months ago

Hello.

The code is simple and clean, I like it, but
Xcode tells me data the data is nil, and it’s not the URL, it works when I test it on my browser…

Any ideias on what’s happening?

Thanks.

Robbie Heller
6 months ago

You need the URL to point your your sever.

mouni
2 months ago

sir how to get data from url

mouni
2 months ago

im not understanding your code …iam new iOS developer so please help me

Show more replies

Subscribe to our weekly newsletter