Search code examples
iosobjective-cmemory-managementsdwebimage

App crash while downloading large images using SDWebImage?


I'm using SDWebImage to download image async from server.Some images on server are of size ~1.5 to 2. MB.I'm showing these images on UICollectionView. I'm getting memory warning and app crashes after several run.Some times it happens when images downloaded first time and some time when i scroll the collection view up and down. Here is my code-

-(void)setImageWithUrl:(NSURL*)imgurl onImageView:(UIImageView*)image prograssive:(BOOL)progressive
{
    __block UIActivityIndicatorView *activityIndicator;
    __weak UIImageView *weakImageView = image;
    SDWebImageOptions opt;
    if (progressive) {

        opt = SDWebImageProgressiveDownload;
    }
    else
        opt = SDWebImageRetryFailed;
    [image sd_setImageWithURL:imgurl placeholderImage:[UIImage imageNamed:@"default_image"] options:opt progress:^(NSInteger receivedSize, NSInteger expectedSize)
     {
         if (!activityIndicator)
         {
             [weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
             activityIndicator.center = CGPointMake(weakImageView.frame.size.width /2, weakImageView.frame.size.height/2);
             // activityIndicator.center = weakImageView.center;
             [activityIndicator setBackgroundColor:[UIColor clearColor]];
             [activityIndicator startAnimating];
         }
     }
                    completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
     {
         [activityIndicator removeFromSuperview];
         activityIndicator = nil;
     }];
}

and in AppDelegate-

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{

    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] cleanDisk];
    [[SDImageCache sharedImageCache] clearDisk];
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
}

Please not the images are high resolution(more than 3000 pixel width).For example one of them has 4256*2832 and size 979KB produce the memory warning.Any help or suggestion would be appreciated. EDIT:- my App is being killed due to memory pressure, but only on iPhone 4s and lower versions(working fine on iPhone5 and above).when a large image is being downloaded(or complete download) i got a sudden memory spike(it goes from ~25mb to ~90mb) and app crashes.Any suggestion what to do?


Solution

  • It sounds like your App is being killed due to memory pressure. Check Instruments where exactly the memory increases and maybe try using an Autorelease Pool to mitigate any memory spikes.