8

我正在尝试优化我的应用程序中的负载,事实上,我的应用程序中加载了很多图像,我花了很多时间等待视图控制器打开,尤其是第一个初始视图,其中包含很多的图像。

我看了看苹果样品

但我不能重新工作整个应用程序,我想要的只是具体告诉我我应该做什么?,我实施?

在 中tableview,其中实现了单元格cellforrowatindexpath:

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

我能做点什么吗?

谢谢您的帮助!

在此处输入图像描述

4

9 回答 9

6

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;
    });
});
于 2013-06-26T11:21:23.003 回答
3

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.

于 2013-06-26T11:22:29.843 回答
2

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;
于 2013-06-26T11:20:33.273 回答
2

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

于 2013-06-26T11:21:00.710 回答
2

您可以在NSOperationQueue上查看本教程,而GCD上的本教程完全相同。您也可以尝试使用:

// 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;
    });
});
于 2013-06-26T11:25:32.593 回答
0

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];
                            });
                        });
于 2013-06-26T11:22:10.783 回答
0

您可以使用异步图像视图。

- (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;
    });
}

看看这个链接。你会对使用异步图像视图有一个想法。

于 2013-06-26T11:23:52.117 回答
0

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;
    });
});
}
于 2014-12-23T10:35:09.343 回答
0

使用 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];
        }
于 2015-06-19T02:55:46.357 回答