在 iOS 中加載網絡圖片有多種實現方式,各有優劣。本文對比三種常見方案,並給出各自的適用場景。
// [self.icon setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:tempUrl]]];
這是最基礎、也是最少人使用的方式。它的致命問題在於:網絡狀況不佳時會阻塞當前線程,導致程式出現「假死」,使用者體驗極差。因此這種同步加載方式基本只適合學習理解原理,實際開發中不建議使用。
把下載任務放到後台異步隊列執行,下載完成後再切回主線程更新 UI:
-(void)imageDownLoadByUrlASYNC:(NSURL *)url Complete:(complete)finished {
// 異步並列執行
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = nil;
NSError *error;
NSData *responseData = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&error];
image = [UIImage imageWithData:responseData];
// 跳回主線程執行
dispatch_async(dispatch_get_main_queue(), ^{
// 在主線程中進行 UI 操作
finished(image);
});
});
}
這種方式與方式一的下載邏輯相同,但通過 dispatch_async 把耗時操作放到異步隊列,下載完成拿到 image 後再回主線程回調、設置 image,從根本上避免了阻塞主線程的問題。
這是一種更先進的方案——借助 CGImageSource 在數據下載的過程中「邊接收邊渲染」,讓圖片逐步呈現出來,顯著提升使用者體驗。核心是創建一個 NSURLConnection 並實現其代理方法:
#pragma mark -- NSURLConnectionDataDelegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_expectedLeght = response.expectedContentLength;
NSString *mimeType = response.MIMEType;
NSArray *arr = [mimeType componentsSeparatedByString:@"/"];
if (arr.count < 1 || ![[arr objectAtIndex:0] isEqual:@"image"]) {
NSLog(@"not a image url");
[connection cancel];
_conn = nil;
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Connection %@ error, error info: %@", connection, error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
// 若下載數據尚未完整,生成最終圖片
if (!_isLoadFinished) {
CGImageSourceUpdateData(_incrementallyImgSource, (CFDataRef)_recieveData, _isLoadFinished);
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementallyImgSource, 0, NULL);
UIImage *image = [UIImage imageWithCGImage:imageRef];
[self.icon setImage:image];
CGImageRelease(imageRef);
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_recieveData appendData:data];
_isLoadFinished = false;
if (_expectedLeght == _recieveData.length) {
_isLoadFinished = true;
}
CGImageSourceUpdateData(_incrementallyImgSource, (CFDataRef)_recieveData, _isLoadFinished);
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementallyImgSource, 0, NULL);
UIImage *image = [UIImage imageWithCGImage:imageRef];
[self.icon setImage:image];
CGImageRelease(imageRef);
}
這種方式經過測試非常好用,在用戶體驗上有明顯提升。它的關鍵在於:每接收到一段數據就調用 CGImageSourceUpdateData 更新數據源,再通過 CGImageSourceCreateImageAtIndex 生成當前階段的最新圖片並刷新顯示,從而實現漸進式加載的效果。當然,由於是較新的嘗試,實際使用中仍需留意邊界情況與潛在問題。
對比總結:方式一簡單但會卡主線程,僅供理解;方式二異步加載是通用且穩妥的做法;方式三漸進式加載則能在較慢網絡下帶來最佳的使用者體驗。而在現代 iOS 開發中,我們通常會直接使用 SDWebImage 等成熟的三方庫,它們在異步下載、漸進加載和緩存策略上都做了完善封裝。