Gabriel
Gabriel

Reputation: 328

Easy Asynchronous Image Download UIImage View

I have an app i am building it works fine but the image source i am using is from a website and when I switch back to my initial view it takes quite some time for it to load. My question is would there be a way to get this done and have the speed be faster. here is the code I use to pull my image source

////Loads UIImageView from URL
todaysWallpaper.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.inkdryercreative.com/daily/archive/mondays/images/062-mondays-960x640-A.jpg"]]];

any help or a shove in the proper direction. Soon the image will change every time day as well so any help/thoughts on that would be of great appreciation.

Upvotes: 1

Views: 3508

Answers (2)

Leo
Leo

Reputation: 1005

wrap the UIImage creation in a block running asynchronously (code assumes ARC) which in turn calls your callback in the main thread

@implementation Foo
...
Foo* __weak weakSelf=self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:
                   [NSURL  URLWithString:@"http://www.inkdryercreative.com/..jpg"]]];
    dispatch_sync(dispatch_get_main_queue(),^ {
        //run in main thread
       [weakSelf handleDelayedImage:image];
    });
});

-(void)handleDelayedImage:(UIImage*)image
{
   todaysWallpaper.image=image;
}

the weakSelf trick ensures that your Foo class is properly cleaned up even if the URL request is still running

Upvotes: 1

Zoleas
Zoleas

Reputation: 4879

The probleme here is that dataWithContentsOfURL: is on the main thread, so it will block your UI when the image is downloaded.

You have to download it asynchronously. For that I personally use a great piece of code i found on the internet : SDWebImage. It does exactly what you want.

Upvotes: 2

Related Questions