我用一个for循环上传三张照片(用的是afnetworking框架)。
上传它就开了一个线程,上传成功后后台返回一个filename,把filename放进一个数组
我想等三张照片全都上传结束后,对获取到的三个filename进行操作
要怎么做?
NSMutableArray *fileNameArr = [[NSMutableArray alloc]init];
for (int i= 0; i<[self.imgArr count]; i++) {
NSData *data = [self.imgArr objectAtIndex:i];
[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
[formData appendPartWithFileData:data name:@"pic" fileName:fileName mimeType:@"image/jpeg"];
}success:^(AFHTTPRequestOperation *operation,id responseObject){
NSLog(@"success:%@",responseObject);
NSString *str = [[responseObject objectForKey:@"data"] objectForKey:@"fileName"];
[fileNameArr addObject:str];
NSString *ids = [[responseObject objectForKey: @"data"] objectForKey:@"ids"];
}
failure:^(AFHTTPRequestOperation *operation,NSError *error){
NSLog(@"%@",error);
}];
}
第一种是Notification,这个比较解耦。
-(void)viewDidLoad
{
// add a notification observer
[NSNotificationCenter defaultCenter] addObserver:selector:name:object:]
}
-(void)handle
{
if (fileNameArr.count == 3) {
// do something
}
}
NSMutableArray *fileNameArr = [[NSMutableArray alloc]init];
for (int i= 0; i<[self.imgArr count]; i++) {
NSData *data = [self.imgArr objectAtIndex:i];
[manager POST:url
parameters:nil
constructingBodyWithBlock:
^(id<AFMultipartFormData> formData){
[formData appendPartWithFileData:data
name:@"pic"
fileName:fileName
mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation,id responseObject) {
NSLog(@"success:%@",responseObject);
NSString *str = [[responseObject objectForKey:@"data"] objectForKey:@"fileName"];
[fileNameArr addObject:str];
NSString *ids = [[responseObject objectForKey: @"data"] objectForKey:@"ids"];
// add here
[NSNotificationCenter defaultCenter] postNotificationName:object:]
} failure:^(AFHTTPRequestOperation *operation,NSError *error){
NSLog(@"%@",error);
}];
}
第二种就是,GCD啦,但是代码看起来耦合比较高。
NSMutableArray *fileNameArr = [[NSMutableArray alloc]init];
for (int i= 0; i<[self.imgArr count]; i++) {
NSData *data = [self.imgArr objectAtIndex:i];
[manager POST:url
parameters:nil
constructingBodyWithBlock:
^(id<AFMultipartFormData> formData){
[formData appendPartWithFileData:data
name:@"pic"
fileName:fileName
mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation,id responseObject){
NSLog(@"success:%@",responseObject);
NSString *str = [[responseObject objectForKey:@"data"] objectForKey:@"fileName"];
[fileNameArr addObject:str];
NSString *ids = [[responseObject objectForKey: @"data"] objectForKey:@"ids"];
// here
if (fileNameArr.count == 3) {
dispatch_async(dispatch_get_main_queue(), ^{
// handle
});
}
} failure:^(AFHTTPRequestOperation *operation,NSError *error){
NSLog(@"%@",error);
}];
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。