Reputation:
NSURL *jsonURL = [NSURL URLWithString:stringURL];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSString *stringImageURL = [jsonArray valueForKey:@"artworkUrl100"];
The last line is the issue. I can get the array perfectly fine but the value of stringImageURL
is nil. How do I correctly retrieve the key highlighted below?
Upvotes: 2
Views: 2114
Reputation: 19030
NSString *stringImageURL = [jsonArray valueForKey:@"artworkUrl100"];
Should be
NSString *stringImageURL = [[[jsonArray valueForKey:@"result"]
objectAtIndex:0]
valueForKey:@"artworkUrl100"];
Or, more concisely
NSString *stringImageURL = jsonArray[@"result"][0][@"artworkUrl100"];
The data was nested 2 levels deeper than you thought, the dictionary value you were after was contained within an array, in another dictionary, under the key result
.
Upvotes: 3
Reputation: 16124
First off, your jsonArray is not an array, but a dictionary.
Second, looks like you have a dictionary with an array of dictionaries, so it would be:
NSArray *resultsArray = [jsonArray valueForKey:@"results"];
NSDictionary *resultDict = [resultsArray objectAtIndex:0];
NSString *stringImageURL = [resultDict valueForKey:@"artworkUrl100"];
Upvotes: 1