1.用SDWebImage下載圖片
#import "SDWebImageManager.h" [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:@"anurl"] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) { //處理下載進度 } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { completedCount ++ ; if (error) { DDLogDebug(@"error is %@",error); } if (image) { //圖片下載完成 在這里進行相關操作,如加到數組里 或者顯示在imageView上 } } }];
2.圖片緩存
//需要導入的頭文件 #import "SDImageCache.h" UIImage *image = [UIImage imageNamed:@"home_btn_skip"]; [[SDImageCache sharedImageCache] storeImage:image forKey:@"anUrlString" toDisk:NO]; //下方是用SDWebimage加載剛剛緩存的圖片 // UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0 ,300 ,300 )]; // [imageView setImageWithURL:[NSURL URLWithString:@"anUrlString"]]; // [self.view addSubview:imageView];
在
[[SDImageCache sharedImageCache] storeImage:image forKey:@"anUrlString" toDisk:NO];
這個方法中forkey 是image緩存所對應的鍵 一般都是與一張圖片的url對應。toDisk 是說是否緩存到本地。SDWebimage 下載圖片時候會先去緩存根據提供的url尋找緩存中是否有這個圖片 如果有就加載 ,如果沒有就進行網絡請求。