我查过在论坛里有关iOS批量上传文件问答,最后还是用了Dispatch Groups和AFFile 里面的fileWithName:contentsAtPath:来处理批量上传的问题,每上传成功一个文件,就把返回来的file.url放进一个数组里面。
但是这样又有个问题:因为是异步处理,返回来的file.url的顺序有可能被打乱,有没有什么解决方法?下面贴上现在写的部分代码:
-(void)uploadImage{
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *directory = [documentsDirectory stringByAppendingPathComponent:@"/MyProcess"];
NSError *error = nil;
//create group
dispatch_group_t group = dispatch_group_create();
//循环读取文件夹里面的每个文件名
for (NSString *fileName in [fm contentsOfDirectoryAtPath:directory error:&error]) {
NSString *filePath = [NSString stringWithFormat:@"%@/%@", directory, fileName];
dispatch_group_enter(group);
AVFile *file = [AVFile fileWithName:fileName contentsAtPath:filePath];
[file saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
//urlList是用来放置返回来的file.url
[_urlList addObject:file.url];
dispatch_group_leave(group);
}];
}
//当全部文件上传成功后,调用该函数
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSLog(@"finally!");
});
}