把一張網路圖片載下來顯示在 UIImageView 上,是每個 iOS 新手都會寫的功能。看似簡單,但寫法差很多,效能與使用者體驗也差很多。
在 ViewController.h 中關聯一個 image view 與一個 button:
@property (weak, nonatomic) IBOutlet UIImageView *showImageView; - (IBAction)loadImage:(id)sender;
這是最推薦的直覺寫法。下載放在背景佇列,UI 更新切回主線程:
- (IBAction)loadImage:(id)sender {
NSURL *url = [NSURL URLWithString:@"https://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];
dispatch_queue_t queue = dispatch_queue_create("loadImage", NULL);
dispatch_async(queue, ^{
NSData *resultData = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:resultData];
dispatch_async(dispatch_get_main_queue(), ^{
self.showImageView.image = img;
});
});
}
注意這裡用的是 dispatch_async 回主線程,而不是 dispatch_sync。若在主線程對主線程做 sync 會直接死鎖。
- (IBAction)loadImage:(id)sender {
NSURL *url = [NSURL URLWithString:@"https://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];
NSData *resultData = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:resultData];
self.showImageView.image = img;
}
程式碼最短,但 dataWithContentsOfURL: 會阻塞呼叫它的執行緒。放在主線程就是畫面凍住,網路稍慢使用者就會以為 App 當機,甚至被系統 watchdog 判定無回應而終止。教學可以,正式專案請避免。
需要知道下載進度、或想在失敗時處理錯誤,就用委派式連線。先在 header 準備一個暫存用的 NSMutableData:
@property (nonatomic, retain) NSMutableData *mutableData; @property (weak, nonatomic) IBOutlet UIImageView *showImageView; - (IBAction)loadImage:(id)sender;
- (IBAction)loadImage:(id)sender {
NSURL *url = [NSURL URLWithString:@"https://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"GET"]; // 請求方式
[request setTimeoutInterval:60]; // 逾時時間
self.mutableData = [[NSMutableData alloc] init];
[NSURLConnection connectionWithRequest:request delegate:self]; // 送出非同步請求
}
#pragma mark - NSURLConnection delegate
// 資料陸續到齊時被呼叫
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.mutableData appendData:data];
}
// 下載完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
UIImage *image = [UIImage imageWithData:self.mutableData];
self.showImageView.image = image;
}
// 失敗
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"請求網路失敗:%@", error);
}
單純抓一張圖,寫法一最省事;需要進度與錯誤處理,寫法三能滿足。不過要提醒的是,NSURLConnection 自 iOS 9 起已被蘋果標記為棄用,新專案請改用 NSURLSession:用 NSURLSessionDataTask 搭配 NSURLSessionDataDelegate,概念與寫法三幾乎一一對應,同時支援背景傳輸與更好的快取控制。若專案會大量載入圖片(例如列表縮圖),直接採用 SDWebImage 這類成熟套件會比自己實作快取與併發控制划算得多。