從網路抓圖片是幾乎每個 App 都會做的事。以下兩段程式碼示範最基本的下載與縮放流程。
- (UIImage *)getImageFromURL:(NSString *)theURL {
UIImage *theImage = NULL;
NSString *imageFileName = [BT_strings getFileNameFromURL:theURL];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:theURL]];
theImage = [[UIImage alloc] initWithData:imageData];
[BT_fileManager saveImageToFile:theImage fileName:imageFileName];
return theImage;
}
NSString *imageURL = [NSString stringWithFormat:@"https://theimageurl.com/?id=%@",
[[resultsEntries objectAtIndex:0] objectForKey:@"image_large"]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageURL]];
UIImage *image = [[UIImage alloc] initWithData:imageData];
// 縮放為 100x100
CGSize newSize = CGSizeMake(100, 100);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageHeight = image.size.height;
[imageMain setImage:newImage];
[imageData release];
[image release];
這兩段程式碼都用了 initWithContentsOfURL:,這是同步的網路請求——它會阻塞呼叫的執行緒。若放在 viewDidLoad 或 cellForRowAtIndexPath 中,網路稍慢就會讓 UI 完全凍住,使用者會以為 App 當掉了。正式環境請改用 NSURLSession 的 dataTaskWithURL:completionHandler:,並把解碼與縮放也一併放到背景佇列,只把 setImage 這一步回主執行緒。
另外兩個細節:一是 URL 中的中文或空白必須先做字元轉義(stringByAddingPercentEscapesUsingEncoding: 或改用 NSURLComponents),否則 request 會直接失敗;二是縮放時若來源與目標比例不同,直接 drawInRect 會導致變形,需要改用 Aspect Fill 加上 Center Crop 的算法。