在iOS中加載網絡圖片有多種方式:
法1:在主線程中同步加載網絡圖片
在主線程中加載圖片,先將圖片的URL存放進NSURL,然後再用這個NSURL初始化NSData,再把UIImage用NSData初始化,就行了。代碼如下:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
if ([tableView isEqual:self.tableView]) {
cell.textLabel.text = @"Synchronized Loading";
// synchronized image loading
NSURL *imageURL = [NSURL URLWithString:@"http://www.i-programmer.info/images/stories/News/2011/MARCH/CMULOGO.jpg"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
cell.imageView.image = [UIImage imageWithData:imageData];
}
return cell;
}
但是這種方法會阻塞主線程,也就是隻有等圖片這段代碼執行後,頁面才能夠被進入。
法2:使用NSOperationQueue異步加載
一個NSOperationQueue 操作隊列,就相當於一個線程管理器,而非一個線程。因爲你可以設置這個線程管理器內可以並行運行的的線程數量。代碼如下:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"NSOperationQueue異步加載";
[self.view addSubview:self.tableView];
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImage) object:nil];
[operationQueue addOperation:op];
}
- (void)downloadImage {
NSURL *imageURL = [NSURL URLWithString:@"http://www.iconpng.com/png/socialnetworks2/linkedin.png"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
}
- (void)updateUI:(UIImage*)image {
self.image = image;
[self.tableView reloadData];
}
法3:Cache緩存+同步加載
第一次加載的時候用同步加載,同時把圖片緩存到沙箱目錄中,第二次及以後的加載就直接從本地目錄中加載。
1)首先建立一個緩存目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString * diskCachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"imageCache"];
//如果目錄imageCache不存在,創建目錄
if (![[NSFileManager defaultManager] fileExistsAtPath:diskCachePath]) {
NSLog(@"fuck1");
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:diskCachePath withIntermediateDirectories:YES attributes:nil error:&error];
}
2)如果本地緩存沒有,則保存圖片到對應的路徑。若本地緩存有圖片,則直接從緩存中加載圖片
<pre name="code" class="objc"> for (int i = 0; i < self.urlArray.count; i++) {
NSURL *imageURL = self.urlArray[i];
// 如果本地緩存沒有,保存圖片
NSString *localPath = [NSString stringWithFormat:@"%@/headimage%d.png", diskCachePath, i];
if (![[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
[imageData writeToFile:localPath atomically:YES];
}
// 如果存在本地緩存圖片,直接讀取cache內的緩存圖片
if ([[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
NSData *data = [NSData dataWithContentsOfFile:localPath];
UIImage *image = [UIImage imageWithData:data];
[self.imageArray addObject:image];
}
}
我寫的Demo的下載地址如右:http://download.csdn.net/detail/luoshengkim/9481601
關於iOS多線程編程,可以參考這個鏈接:http://blog.csdn.net/totogo2010/article/details/8013316