Nithinbemitk
Nithinbemitk

Reputation: 2730

Taking time to load the image from URL to UIImageview

I am using this code for displaying the image from URL to UIImageview

UIImageView *myview=[[UIImageView alloc]init];

myview.frame = CGRectMake(50, 50, 320, 480);

NSURL *imgURL=[[NSURL alloc]initWithString:@"http://soccerlens.com/files/2011/03/chelsea-1112-home.png"];

NSData *imgdata=[[NSData alloc]initWithContentsOfURL:imgURL];

UIImage *image=[[UIImage alloc]initWithData:imgdata];

myview.image=image;

[self.view addSubview:myview];

But the problem is that its taking too long time to display the image in imageview.

Please help me...

Is there any method to fast the process...

Upvotes: 2

Views: 2591

Answers (3)

Master Stroke
Master Stroke

Reputation: 5128

The answers given to me on my own question Understanding the behaviour of [NSData dataWithContentsOfURL:URL] inside the GCD block does makes sense.So be sure that if you use [NSData dataWithContentsOfURL:URL] inside the GCD(as many developers do these days) is not a great idea to download the files/images.So i am leaning towards the below approach(you can either use NSOperationQueue).

Load your images using [NSURLConnection sendAsynchronousRequest:queue:completionHandler: then use NSCache to prevent downloading the same image again and again.

As suggested by many developers go for SDWebimage and it does include the above strategy to download the images files .You can load as many images you want and the same URL won't be downloaded several times as per the author of the code

EDIT:

Example on [NSURLConnection sendAsynchronousRequest:queue:completionHandler:

NSURL *url = [NSURL URLWithString:@"your_URL"];
NSURLRequest *myUrlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:myUrlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{

    if ([data length] > 0 && error == nil)
        //doSomething With The data

    else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
        //time out error

    else if (error != nil)
        //download error
}];

Upvotes: 1

Fahim Parkar
Fahim Parkar

Reputation: 31637

Instead of dispatch_async, Use SDWebImage for caching the images.

This is best I have seen...

The problem of dispatch_async is that if you lost focus from image, it will load again. However SDWebImage, Caches the image and it wont reload again.

Upvotes: 2

Aniket Kote
Aniket Kote

Reputation: 541

Use Dispatch queue to load image from URL.


dispatch_async(dispatch_get_main_queue(), ^{

  });

Or add a placeholder image till your image gets load from URL.

Upvotes: 1

Related Questions