简体   繁体   中英

Loading images in background to optimize the loading in ios

I am trying to optimize the load in my application, in fact, I have a lot of images that loaded in my application, and I spend a lot of time waiting for a view controller to open, especially the first initial view which includes a lot of images.

I took a look at apple sample

but I cannot re-work the whole application, what I want is just to tell me specifically what should I do?, I implement?

in the tableview , where the cell is implemented cellforrowatindexpath:

 NSURL *imageURL = ......;
 NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
 UIImage *imageLoad;
 imageLoad = [[UIImage alloc] initWithData:imageData];
 imageView.image = imageLoad;

could I do something?

thank you for your help!

在此输入图像描述

Try this code:

dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
    /* Fetch the image from the server... */
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *img = [[UIImage alloc] initWithData:data];
    dispatch_async(dispatch_get_main_queue(), ^{
        /* This is the main thread again, where we set the tableView's image to
         be what we just fetched. */
        cell.imgview.image = img;
    });
});

Yes, you can add placeholder image to it.

It will not slow down the scrolling and will load image accordingly with time.

Also import this file UIImageView+WebCache.m and MapKit Framework

Here is the link to download the files.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }
    UIImageview*  iV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
   [iV setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"image_placeholder.gif"]];
   [cell.contentView addSubview:iV];
   [iV release];

}

Just clean, build and run.

Take a look at this control: https://github.com/nicklockwood/AsyncImageView

It's very easy to implement (only 1 header file) and will suit your needs just fine.

Using this control: Instead of declaring:

NSURL *imageURL = ......;
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *imageLoad;
imageLoad = [[UIImage alloc] initWithData:imageData];
imageView.image = imageLoad;

Use:

NSURL *imageURL = ......;
imageView.imageURL = imageURL;

To enable the app while getting the images from server and disable block while loading the images try to use UIImageView+AFNetworking library to load the image from server asynchronously AFNetworking

   NSString *imageUrl = [[dict objectForKey:@"photo"] objectForKey:@"url"];

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

   [myImage setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage    imageNamed:@"PlaceHolder.png"]];

Just add this library and include the UIImageView+AFNetworking so you can use the new UIImageView Category imageWithUrl

you can check this tutorial on NSOperationQueue and this on GCD doing exactly same. Also you can try using:

// Block variable to be assigned in block.
__block NSData *imageData;
dispatch_queue_t backgroundQueue  = dispatch_queue_create("com.razeware.imagegrabber.bgqueue", NULL);

// Dispatch a background thread for download
dispatch_async(backgroundQueue, ^(void) {
    imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *imageLoad;
    imageLoad = [[UIImage alloc] initWithData:imageData];

    // Update UI on main thread
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        imageView.image = imageLoad;
    });
});

You can try something like this!....

 dispatch_queue_t checkInQueueForPostImage = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);

                        dispatch_async(checkInQueueForPostImage, ^{
                            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:postAndCheckInDetails.postImageURL]]];

                            dispatch_sync(dispatch_get_main_queue(), ^{
                                if (image!=nil) {
                                    [uploadImage setImage:image];
                                }

                                [cell setNeedsLayout];
                            });
                        });

You can use async imageview.

- (void) loadImageFromURL:(NSURL*)url placeholderImage:(UIImage*)placeholder cachingKey:(NSString*)key {
    self.imageURL = url;
    self.image = placeholder;

    NSData *cachedData = [FTWCache objectForKey:key];
    if (cachedData) {   
       self.imageURL   = nil;
       self.image      = [UIImage imageWithData:cachedData];
       return;
    }

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
        NSData *data = [NSData dataWithContentsOfURL:url];

        UIImage *imageFromData = [UIImage imageWithData:data];

        [FTWCache setObject:data forKey:key];

        if (imageFromData) {
            if ([self.imageURL.absoluteString isEqualToString:url.absoluteString]) {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    self.image = imageFromData;
                });
            } else {
//              NSLog(@"urls are not the same, bailing out!");
            }
        }
        self.imageURL = nil;
    });
}

Take a look at this link .You will have an idea on using async imageview.

Here is a slightly modified approach of Ramu Pasupoletis answer. I added the __block modifier to make the var img visible inside the block called on the main thread. Here is the complete method definition which I use in

-(UITableViewCell*)cellforRowAtIndexPath:(UIIndexPath*)indexPath;

for fetching the thumbnails lazily. I also added placeholders there for the cells UIImageViews.

//lazy loading of thumbnails for images in cell via bg thread
-(void)loadImageForCell:(CustomEditTableViewCell*)theCell withFilepath: (NSString*)filepath{

dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
    UIImage (__block *img) = [UIImage imageWithContentsOfFile:filepath];
    UIImage *thumbnail = [[GlobalFunctions sharedGlobalFunctions] imageOfSize:CGSizeMake(40, 40) fromImage:img];
    dispatch_async(dispatch_get_main_queue(), ^{
        theCell.imageView.image = thumbnail;
    });
});
}

Use IDAsyncImageView.h

 //////////////////////////////////////
    IDAsyncImageView.h
 /////////////////////////////////////

        @interface IDAsyncImageView : NSObject

        @property (nonatomic, strong) NSCache *cache;    

        + (instancetype)instance;

        - (void)loadImageView:(UIImageView*)imageView withURLString:(NSString *)urlString;

        @end

    //////////////////////////////////////
    IDAsyncImageView.m
    /////////////////////////////////////

        #import "IDAsyncImageView.h"



            @implementation IDAsyncImageView

                + (instancetype)instance
                {
                    static IDAsyncImageView *_instance = nil;
                    static dispatch_once_t onceToken;
                    dispatch_once(&onceToken, ^{
                        _instance = [[self alloc] init];
                });
                return _instance;
            }

        - (instancetype)init
        {
            self = [super init];
            if (self) {
                self.cache =  [[NSCache alloc] init];
            }

            return self;
        }

        - (void)loadImageView:(UIImageView*)imageView withURLString:(NSString *)urlString
        {
            UIActivityIndicatorView* activityView;
            activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            activityView.hidesWhenStopped = YES;
            activityView.center = CGPointMake(imageView.bounds.size.width / 2.0f, imageView.bounds.size.height / 2.0f);
            activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
            [imageView addSubview:activityView];
            [activityView startAnimating];

            UIImage* imageLoad = [self.cache objectForKey:urlString];
            if (nil != imageLoad) {
                imageView.image = imageLoad;
                [activityView removeFromSuperview];
            }
            else {

            // Block variable to be assigned in block.
            __block NSData *imageData;

            // Dispatch a background thread for download
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
                UIImage* imageLoad = [[UIImage alloc] initWithData:imageData];

                // Update UI on main thread
                dispatch_async(dispatch_get_main_queue(), ^(void) {
                    [self.cache setObject:imageLoad forKey:urlString];
                    imageView.image = imageLoad;
                    [activityView removeFromSuperview];
                });
            });
            }
        }

    //////////////////////////////////////
    ViewController.m
    //////////////////////////////////////

        - (void)viewDidLoad {
        [super viewDidLoad];
        [[IDAsyncImageView instance] loadImageView:myImageView withURLString:aUrl];
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM