在 UIScrollView 或列表裡同步抓網路圖片會直接卡住主執行緒。以下三種做法從最原始到比較完整的封裝,可以依專案規模挑用。
用 NSURLConnection 分次接收資料,完成後才建立 image view,是最直觀的非同步寫法。
// AsyncImageView.h
#import <UIKit/UIKit.h>
@interface AsyncImageView : UIView {
NSURLConnection *connection;
NSMutableData *data;
}
- (void)loadImageFromURL:(NSURL*)url;
@end
// AsyncImageView.m
#import "AsyncImageView.h"
@implementation AsyncImageView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) { }
return self;
}
- (void)loadImageFromURL:(NSURL*)url {
if (connection != nil) { [connection release]; }
if (data != nil) { [data release]; }
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
if (data == nil) {
data = [[NSMutableData alloc] initWithCapacity:2048];
}
[data appendData:incrementalData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {
[connection release];
connection = nil;
if ([[self subviews] count] > 0) {
[[[self subviews] objectAtIndex:0] removeFromSuperview];
}
UIImageView *imageView =
[[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
[self addSubview:imageView];
imageView.frame = self.bounds;
[imageView setNeedsLayout];
[self setNeedsLayout];
[data release];
data = nil;
}
- (UIImage*)image {
UIImageView *iv = [[self subviews] objectAtIndex:0];
return [iv image];
}
- (void)dealloc {
[connection cancel]; // 別忘了取消,否則回收後仍會收到回調
[connection release];
[data release];
[super dealloc];
}
@end
用 GCD 把下載丟到背景佇列,回主執行緒設定 image,同時支援縮放與疊 logo。
@interface UIButton (AsyncImage)
- (void)setImageFromURL:(NSString *)urlString adjustToSize:(CGSize)size
completion:(void (^)(void))completion logo:(UIImage *)logoImage;
@end
@implementation UIButton (AsyncImage)
- (void)setImageFromURL:(NSString *)urlString adjustToSize:(CGSize)size
completion:(void (^)(void))completion logo:(UIImage *)logoImage {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = nil;
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
image = [UIImage imageWithData:data];
if (image) {
if (!CGSizeEqualToSize(size, CGSizeZero)) {
image = [UIImage imageWithCGImage:image.CGImage
scale:[self scaleImage:image adjustToSize:size]
orientation:image.imageOrientation];
}
if (logoImage) {
image = [self addLogoImage:logoImage toImage:image];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self setImage:image forState:UIControlStateNormal];
if (completion) completion();
});
} else {
NSLog(@"async load error.");
}
});
}
// 計算放大倍率,使圖片能填滿按鈕
- (CGFloat)scaleImage:(UIImage *)image adjustToSize:(CGSize)size {
CGFloat xScale = size.width / image.size.width;
CGFloat yScale = size.height / image.size.height;
return 1.0 / MIN(xScale, yScale);
}
// 在右上角疊上 logo
- (UIImage *)addLogoImage:(UIImage *)logo toImage:(UIImage *)img {
CGFloat scale = [UIScreen mainScreen].scale;
int w = scale * img.size.width;
int h = scale * img.size.height;
int logoWidth = logo.scale * logo.size.width;
int logoHeight = logo.scale * logo.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace,
kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
CGContextDrawImage(context, CGRectMake(w - logoWidth, 0, logoWidth, logoHeight), [logo CGImage]);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked scale:scale orientation:img.imageOrientation];
}
@end
前面兩種都沒有快取,同一張圖捲動來回會反覆下載。這個版本加上磁碟快取、並限制同時下載數為 2,還支援插隊與清除舊任務。
// ImageManager.h
#import <Foundation/Foundation.h>
#import "StringUtils.h"
@interface ImageManager : NSObject {
NSMutableDictionary *_imageDict; // imageName -> imageView,等待中的對應關係
NSMutableArray *_imageArr; // 等待下載的佇列
}
@property (nonatomic, strong) NSString *httpUrl;
@property (nonatomic, strong) NSMutableDictionary *imageDict;
@property (nonatomic, assign) dispatch_queue_t networkQueue;
+ (ImageManager *)sharedInstance;
- (void)asyncImage:(NSString *)imageName imageView:(UIImageView *)imageView;
- (void)asyncImageInsert:(NSString *)imageName imageView:(UIImageView *)imageView insert:(BOOL)insert;
- (void)asyncImageCleanOld:(NSString *)imageName imageView:(UIImageView *)imageView cleanOld:(BOOL)cleanOld;
@end
// ImageManager.m
#import "ImageManager.h"
@interface ImageManager()
@end
@implementation ImageManager
static int counter = 0; // 目前進行中的下載數
@synthesize imageDict = _imageDict;
+ (ImageManager *)sharedInstance {
static id instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ instance = self.new; });
return instance;
}
- (id)init {
if ((self = [super init])) {
self.networkQueue = dispatch_queue_create("com.warrior.network.image", nil);
_imageDict = [[NSMutableDictionary alloc] init];
_imageArr = [[NSMutableArray alloc] init];
}
return self;
}
- (NSString *)fileFullPath:(NSString *)fileName {
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
return [NSString stringWithFormat:@"%@/%@", cachePath, fileName];
}
// 清除舊任務後再排入
- (void)asyncImageCleanOld:(NSString *)imageName imageView:(UIImageView *)imageView cleanOld:(BOOL)cleanOld {
if (cleanOld) { [_imageArr removeAllObjects]; }
[self asyncImage:imageName imageView:imageView];
}
- (void)asyncImageInsert:(NSString *)imageName imageView:(UIImageView *)imageView insert:(BOOL)insert {
if ([StringUtils isEmpty:imageName]) { return; }
NSString *cacheKey = [imageName stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
NSData *data = [NSData dataWithContentsOfFile:[self fileFullPath:cacheKey]];
if (data == nil) {
[_imageDict setValue:imageView forKey:imageName];
if (insert) { [_imageArr insertObject:imageName atIndex:0]; } // 插隊
else { [_imageArr addObject:imageName]; }
[self cacheImage];
} else {
[imageView setImage:[UIImage imageWithData:data]]; // 命中快取
}
}
- (void)asyncImage:(NSString *)imageName imageView:(UIImageView *)imageView {
[self asyncImageInsert:imageName imageView:imageView insert:NO];
}
- (void)cacheImage {
// 最多同時兩個下載
for (; counter < 2 && _imageArr.count > 0; counter++) {
NSString *imageName = nil;
@synchronized(self) {
imageName = [[_imageArr objectAtIndex:0] copy];
[_imageArr removeObjectAtIndex:0];
}
if (imageName == nil) continue;
dispatch_async(self.networkQueue, ^{
NSLog(@"Starting: %@", imageName);
UIImage *avatarImage = nil;
NSString *cacheKey = [imageName stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", self.httpUrl, imageName]];
NSData *responseData = [NSData dataWithContentsOfURL:url];
if (responseData.length > 0) {
[responseData writeToFile:[self fileFullPath:cacheKey] atomically:NO];
avatarImage = [UIImage imageWithData:responseData];
NSLog(@"Finishing: %@", imageName);
if (avatarImage) {
dispatch_async(dispatch_get_main_queue(), ^{
UIImageView *imageView = [_imageDict objectForKey:imageName];
if (imageView != nil) { [imageView setImage:avatarImage]; }
[_imageDict removeObjectForKey:imageName];
});
}
}
counter--;
[self cacheImage];
});
}
}
@end
三個版本的共同重點是:網路 I/O 一律離開主執行緒,UI 更新一律回主執行緒。若要用在真正的列表場景,還要多做兩件事——一是實作「cell 重複使用時取消前一張圖的載入」,否則快速捲動會出現圖片錯位;二是加上記憶體快取(NSCache),把已解碼的 UIImage 留在記憶體中,磁碟快取只能省下網路往返,解碼成本仍在。