iOS 開發中頻繁需要從遠端下載圖片並顯示。本文提供兩種實戰驗證的方法:基礎同步下載與帶縮放的進階版本。注意:生產環境強烈建議使用 SDWebImage、Kingfisher、Nuke 等成熟框架,支援快取、異步、佔位圖、漸進式載入等完整功能。
適用場景:簡單專案、離線快取需求、背景執行緒中呼叫。
缺點:同步阻塞執行緒、無快取策略、無失敗重試、記憶體管理手動。
- (UIImage *)getImageFromURL:(NSString *)theURL {
// 1. 從 URL 取得檔名(作為本地快取鍵值)
NSString *imageFileName = [self getFileNameFromURL:theURL];
// 2. 同步下載資料(會阻塞當前執行緒!)
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:theURL]];
if (!imageData) return nil;
// 3. 建立 UIImage
UIImage *theImage = [[UIImage alloc] initWithData:imageData];
if (!theImage) return nil;
// 4. 儲存至本地沙盒(自定義工具類)
[BT_fileManager saveImageToFile:theImage fileName:imageFileName];
return theImage;
}
// 輔助:從 URL 提取檔名
- (NSString *)getFileNameFromURL:(NSString *)urlString {
NSURL *url = [NSURL URLWithString:urlString];
return [url lastPathComponent];
}
適用場景:縮圖顯示、列表圖片、頻寬敏感環境。
原理:下載原圖 → 繪製至指定尺寸的 Graphics Context → 取得縮放後圖片。
- (UIImage *)downloadAndResizeImageFromURL:(NSString *)imageURL targetSize:(CGSize)targetSize {
// 1. 同步下載(實際專案請改用 NSURLSession 異步)
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageURL]];
if (!imageData) return nil;
UIImage *originalImage = [[UIImage alloc] initWithData:imageData];
if (!originalImage) return nil;
// 2. 建立繪圖上下文進行縮放
UIGraphicsBeginImageContext(targetSize);
[originalImage drawInRect:CGRectMake(0, 0, targetSize.width, targetSize.height)];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 3. 記憶體釋放(MRC 環境下)
[imageData release];
[originalImage release];
return resizedImage;
}
// 使用範例:列表縮圖 100x100
NSString *imageURL = [NSString stringWithFormat:@"https://example.com/image?id=%@", itemID];
UIImage *thumb = [self downloadAndResizeImageFromURL:imageURL targetSize:CGSizeMake(100, 100)];
imageView.image = thumb;
生產級程式碼骨架(NSURLSession + NSCache):
@interface ImageDownloader : NSObject
// 單例
+ (instancetype)sharedDownloader;
// 異步下載,支援進度、完成、取消
- (NSURLSessionDataTask *)downloadImageWithURL:(NSURL *)url
completionHandler:(void (^)(UIImage *image, NSError *error))completion;
// 取消特定 URL 的下載任務
- (void)cancelDownloadForURL:(NSURL *)url;
@end
@implementation ImageDownloader {
NSCache *memoryCache; // 記憶體快取
NSURLSession *session; // 網路會話
NSMutableDictionary *tasks; // 進行中的任務
}
+ (instancetype)sharedDownloader {
static ImageDownloader *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; });
return instance;
}
- (instancetype)init {
self = [super init];
if (self) {
memoryCache = [[NSCache alloc] init];
memoryCache.countLimit = 100;
memoryCache.totalCostLimit = 50 * 1024 * 1024; // 50MB
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReturnCacheDataElseLoad;
config.timeoutIntervalForRequest = 30;
session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
tasks = [NSMutableDictionary dictionary];
}
return self;
}
- (NSURLSessionDataTask *)downloadImageWithURL:(NSURL *)url completionHandler:(void (^)(UIImage *, NSError *))completion {
// 1. 檢查記憶體快取
UIImage *cached = [memoryCache objectForKey:url.absoluteString];
if (cached) {
completion(cached, nil);
return nil;
}
// 2. 檢查是否已有相同任務進行中
NSURLSessionDataTask *existingTask = tasks[url.absoluteString];
if (existingTask) {
// 可選:加入完成回調隊列
return existingTask;
}
// 3. 建立新任務
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[tasks removeObjectForKey:url.absoluteString];
if (error) {
completion(nil, error);
return;
}
if (data && data.length > 0) {
UIImage *image = [UIImage imageWithData:data];
if (image) {
[memoryCache setObject:image forKey:url.absoluteString cost:data.length];
completion(image, nil);
} else {
completion(nil, [NSError errorWithDomain:@"ImageDownloader" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"Invalid image data"}]);
}
} else {
completion(nil, [NSError errorWithDomain:@"ImageDownloader" code:-2 userInfo:@{NSLocalizedDescriptionKey: @"Empty data"}]);
}
}];
tasks[url.absoluteString] = task;
[task resume];
return task;
}
- (void)cancelDownloadForURL:(NSURL *)url {
NSURLSessionDataTask *task = tasks[url.absoluteString];
if (task) {
[task cancel];
[tasks removeObjectForKey:url.absoluteString];
}
}
@end
| 場景 | 推薦方案 |
|---|---|
| 快速原型、內部工具 | 方法一/二(同步簡單) |
| 列表大量圖片、用戶可見介面 | SDWebImage / Kingfisher / Nuke |
| 自定義快取策略、特殊轉換需求 | 自建 ImageDownloader(如上骨架) |
| 大圖漸進式載入、預載入 | Nuke / Kingfisher 進階 API |