經(jīng)常會(huì)遇到這樣的應(yīng)用場(chǎng)景,例如在調(diào)用iOS系統(tǒng)分享功能前(UIActivityViewController),需要將所有的圖片事先準(zhǔn)備好,但是圖片都在網(wǎng)絡(luò)上.
這時(shí),就需要先將圖片都下載好后再進(jìn)行調(diào)用.
可能是這個(gè)功能的實(shí)現(xiàn)太簡單了,所以像SDWebImage,AFNetwork等都沒有提供可以直接調(diào)用的API方法.
所以只好花了2秒鐘自己寫了一個(gè)方法;
#import "ImagesDownloadManager.h"
#import "SDWebImageDownloader.h"
@implementation ImagesDownloadManager
/**
批量下載圖片
保持順序;
全部下載完成后才進(jìn)行回調(diào);
回調(diào)結(jié)果中,下載正確和失敗的狀態(tài)保持與原先一致的順序;
@return resultArray 中包含兩類對(duì)象:UIImage , NSError
*/
+ (void)downloadImages:(NSArray<NSString *> *)imgsArray completion:(void(^)(NSArray *resultArray))completionBlock {
SDWebImageDownloader *manager = [SDWebImageDownloader sharedDownloader];
manager.downloadTimeout = 20;
__block NSMutableDictionary *resultDict = [NSMutableDictionary new];
for(int i=0;i<imgsArray.count;i++) {
NSString *imgUrl = [imgsArray objectAtIndex:i];
[manager downloadImageWithURL:[NSURL URLWithString:imgUrl]
options:SDWebImageDownloaderUseNSURLCache|SDWebImageDownloaderScaleDownLargeImages
progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
} completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
if(finished){
if(error){
//在對(duì)應(yīng)的位置放一個(gè)error對(duì)象
[resultDict setObject:error forKey:@(i)];
}else{
[resultDict setObject:image forKey:@(i)];
}
if(resultDict.count == imgsArray.count) {
//全部下載完成
NSArray *resultArray = [ImagesDownloadManager createDownloadResultArray:resultDict count:imgsArray.count];
if(completionBlock){
completionBlock(resultArray);
}
}
}
}];
}
}
+ (NSArray *)createDownloadResultArray:(NSDictionary *)dict count:(NSInteger)count {
NSMutableArray *resultArray = [NSMutableArray new];
for(int i=0;i<count;i++) {
NSObject *obj = [dict objectForKey:@(i)];
[resultArray addObject:obj];
}
return resultArray;
}
@end
調(diào)用方法:
//下載圖片
[ImagesDownloadManager downloadImages:imgs completion:^(NSArray *resultArray) {
NSMutableArray *items = [NSMutableArray new];
for(int i=0;i<resultArray.count;i++) {
NSObject *obj = [resultArray objectAtIndex:i];
if([obj isKindOfClass:[UIImage class]]) {
//只取UIImage對(duì)象衣屏,其他類型忽略之
[items addObject:obj];
}
}
//調(diào)用系統(tǒng)自帶的分享功能狼忱,把選中的圖片們分享出去
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:nil];
}];