I have an array of 10 URLs that are linked to images of my website.
I'm using SDWebImages for async image downloading and a for loop to run thru the array of URLs. But the code would just run thru the For-loop before the first image can be downloaded. Therefore, the rest of the images never gets downloaded and the new view controller is never displayed
How can I allow the code to run thru the for-loop, and once an image has been downloaded, it pops up a view controller and gets updated whenever a new image is downloaded.
Here's my code:
NewViewController *vc = [[NewViewController alloc] initWithNibName:nil bundle:nil];
NavigationController *navigationController = [[NavigationController alloc] initWithRootViewController:vc];
for (NSString *url in urls) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
[imageView setImageWithURL:[NSURL URLWithString:url]
placeholderImage:[UIImage imageNamed:@"post-imagePlaceholder"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
item.image = image;
[self.images addObject:item];
vc.results = self.images;
;
}
}];
}
[self presentViewController:navigationController animated:YES completion:nil]
A couple of issues jump out at me:
You are creating an new set of image views, but never adding them to any view (e.g. addSubView
).
Furthermore, If these views are in NewViewController
, you should have that controller perform the setImageWithURL
calls (e.g. in it's viewDidLoad
), not the current view controller. The current view controller should simply pass the urls
array to the NewViewController
.
Finally, you are trying to populate an array with the images, but
The way you've written this, I would guess that you're expecting that self.images
will be populated before the new view controller appears. But it won't, because this completed
block happens asynchronously.
You generally shouldn't be populating an array of images anyway, because images require immense amount of memory. If the number of images in your app grows, you'll run across memory warnings. We generally should not maintaining arrays of URLs and let SDWebImage
do the cacheing to efficiently retrieve the images.
So, the current view controller should just pass the urls
array, and the viewDidLoad
of NewViewController
could iterate through those, either (a) finding the appropriate existing image views' IBOutlet
references and call setImageWithURL
; or (b) create a new UIImageView
, set their respective image
and frame
/constraints and add that image view to the new view controller's view. But do not create any images
array.
If not all of the image views are visible at one time, the above approach should be further refined (to only load the image for the visible image views). But hopefully the above answers the immediate question.