Ravi
Ravi

Reputation: 898

How to retrieve images from server asynchronously

i have one NSMutableArray with some image url's. The images have sizes between 12KB to 6MB. I use AsycImageView class and implement but when large images are downloading application get crashed, I gave 6*1024*1024 (6MB) for maxsize in that class, increase time interval 60.0 sec to 180.o sec, but there is no use. I'm getting an error "Received memory warning" and when app crash automatically connection remove from device, but in simulator there is no crash.

Upvotes: 3

Views: 631

Answers (5)

Vaibhav Saran
Vaibhav Saran

Reputation: 12908

you can do this using multiThreading. Here is a code

- (UIImageView *)getImageFromURL:(NSDictionary *)dict
{
    #ifdef DEBUG
    NSLog(@"dict:%@", dict);
    #endif

    UIImageView *_cellImage = nil;
    _cellImage = ((UIImageView *)[dict objectForKey:@"image"]);
    NSString *strURL = [dict objectForKey:@"imageurl"]);

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];

    #ifdef DEBUG
    NSLog(@"%i", data.length);
    #endif

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataFilePath = [NSString stringWithFormat:@"%@.png", [documentsDirectory stringByAppendingPathComponent:[dict objectForKey:@"imageid"]]];

    if (data) // i.e. file exist on the server
    {
        [data writeToFile:dataFilePath atomically:YES];
        _cellImage.image = [UIImage imageWithContentsOfFile:dataFilePath];
    }
    else // otherwise show a default image.
    {
        _cellImage.image = [UIImage imageNamed:@"nouser.jpg"];
    }
    return _cellImage;
}

And call this method in cellForRowAtIndexPath like this:

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:imageURL, @"imageurl", self.imgPhoto, @"image", imageid, @"imageid", nil];
    [NSThread detachNewThreadSelector:@selector(getImageFromURL:) toTarget:self withObject:dict];

The code will start getting images in multiple threads and will save image locally to document folder. Also the image will not download again if already exists with the same name. Hope this helps

Upvotes: 3

apouche
apouche

Reputation: 9983

You're problem seems to be more of a memory usage issue than it is a performance issue.

If you really want to download image asynchronously I would recommend you use The UIImageView category from AFNetworking which has been fully tested and is very well maintained.

However here you run into memory warnings on your device (which obviously holds much less memory than your simulator which runs on your Mac).

So I would use first the static analyzer:

enter image description here

to see if leaks are present and then run a Leaks Instrument to track it down.

Hope this helps.

Upvotes: 0

Paresh Navadiya
Paresh Navadiya

Reputation: 38259

Use GCD for lazy loading.

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
 dispatch_async(queue, ^{
       NSString *strURL = url here;
       NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
       UIImage *image = nil;
       if(data)
        image = [UIImage imageWithData:data];
      dispatch_sync(dispatch_get_main_queue(), ^{
           //now use image in image View  or anywhere according to your requirement.
           if(image)
             yourImgView = image
      });
 });

Upvotes: 3

x4h1d
x4h1d

Reputation: 6092

You could download image asynchronously using GCD. Use the following code,

__block NSData *imageData;

dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, NULL);
dispatch_async(myQueue, ^{
  //load url image into NSData
  imageData = [NSData dataWithContentsOfURL: your_image_URL];
  if(imageData) {
    dispatch_sync(dispatch_get_main_queue(), ^{
        //convert data into image after completion
        UIImage *img = [UIImage imageWithData:imageData];
        //do what you want to do with your image
    });
 } else {
      NSLog(@"image not found at %@", your_image_URL);
 }
});
dispatch_release(myQueue);

For further info, see dispatch_queue_t

Upvotes: 1

Bonnie
Bonnie

Reputation: 4953

I would recommend a drop in replacement API SDWebImage it provides a category for UIImageVIew with support for remote images coming from the web. you can also have a placeholder image till the images are downloaded Asynchronously . Its easy to use and saves a lot of work

Upvotes: 0

Related Questions