I’m trying to put some json images into a UIScrollView and i’m hitting a minor snag.
Im parsing a JSON file into NSDictionary with the native iOS 5 json parser
ScrollView works fine with an NSArray like:
NSArray *immm = [NSArray arrayWithObjects:[UIImage imageNamed:@"cat.png"], [UIImage imageNamed:@"dog1.png"], nil];
for (int i = 0; i < immm.count; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIImageView *subview = [[UIImageView alloc] initWithFrame:frame];
subview.image = [immm objectAtIndex:i];
[self.scrollView addSubview:subview];
}
and the parsing works fine, its a json file I wrote (properly formatted and validated) and returns an NSDictionary in this format (truncated because of long urls, cut and pasted part of the json file but it is properly validated with JSON validator):
{
header = {
main = (
{
img = "http://******.png";
title = Dog;
}
);
};
}
But im making a mistake with the actual JSON data itself, ive tried creating the array before the loop:
NSMutableDictionary *jsonDict = (NSMutableDictionary*)[NSJSONSerialization JSONObjectWithData:theData options:kNilOptions error:&error];
NSLog(@"%@", jsonDict);
theArray = [[jsonDict objectForKey:@"header"] objectForKey:@"main"];
for (NSDictionary *images in theArray){
tempArray = [[ NSMutableArray alloc] initWithObjects:[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: [jsonDict objectForKey:@"img"]]]], nil];
}
and a few other ways but I’ve just hit a brick wall, I’m either getting a blank screen or a crash (cant recreate the damn crash now)
So im not creating the array to be used in the ScrollView properly as it’s NSLog’ing 5 empty variables, not null just empty. Its printing the right amount of nothing tho, 5 images in the JSON file, 5 empty (),
Cheers
You can use the valueForKeyPath: method to grab objects several levels deep in your JSON in one go like this:
The valueForKeyPath method is clever because if it encounters an array it will automatically apply the next bit in the path to every item in that array, which is how we can grab all the img elements inside every object in the main array in one line.
To convert this to an array of images, do the following:
Note: This will take a long time to execute because [NSData dataWithContentsOfURL:URL] may take several seconds to download each URL. You should either run this on a background thread, or use NSURLConnection to do the downloading.
Alternatively, you may want to consider using an asynchronous image downloading library like this one. That will let you assign images to UIImageViews in your interface by URL, and it will download them in the background without blocking your interface.
Example:
This would then load the image automatically, showing a spinner in the imageview while it loads and then fading in the image when it has loaded. It would then be cached for next time if you want to display it again.