NSMutableData to NSDictionary returning null

361 Views Asked by At

I'm writing a program that uses the Instagram API and I'm running into some issues with NSMutableData and NSDictionary.

Since I have to make multiple calls to the API, I decided to create a NSMutableData object, append smaller NSData objects to it and then turn the whole thing into an NSDictionary.

However, after I make a second call to NSMutableData appendData NSData, when I turn NSMutableData into an NSDictionary, the dictionary returns null.

Here's some of my code.

NSMutableData *userData = [[NSMutableData alloc]init]
NSData *feed = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString   stringWithFormat:@"https://api.instagram.com/v1/users/17636367/media/recent?access_token=%@",accessToken]]];
[userData appendData:feed];
NSData *moarData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.instagram.com/v1/users/17636367/media/recent?access_token=%@&max_id=%@",accessToken, maxID]]];
[userData appendData:moarData];
NSDictionary *dictTwo = [NSJSONSerialization JSONObjectWithData:userData options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dictTwo);

dictTwo returns null. However, when I make only one call to appendData, the dictionary isn't empty.

Thanks.

2

There are 2 best solutions below

0
On

The first call will return an array or dictionary. Assuming it is a dictionary you would get something like:

{"some":"data"}

This can be parsed correctly. When you make two calls you get:

{"some":"data"}{"other":"data"}

This is not valid JSON. You need to parse each item separately.

0
On

When you append two separate JSON responses they will not form a JSON.

You can test the final result to see if it is JSON or not with the following link:

JSON validator

You need to parse each query response separately and then apply manipulation on that data: (Ex NSMutableDictionary, NSMutableArray etc).