前台界面先写好需要的参数DIC
#pragma mark 进入界面先刷新数据
-(void)loadData{
NSDictionary *dic1 = @{@"userid":USER_ID,@"current":@"1"};//柚柚
NSDictionary *dic2 = @{@"userid":USER_ID};//推荐同学3行
NSDictionary *dic3 = @{@"userid":USER_ID};//推荐同学6图
NSDictionary *dic4 = @{};//热门话题
NSDictionary *dic5 = @{};//热门活动
NSDictionary *dic6 = @{};//热门院校
NSDictionary *dic7 = @{@"sex":@"1"};//秘柚
NSDictionary *dic8 = @{};//封面人物
NSArray *urls = @[dic1,dic2,dic3,dic4,dic5,dic6,dic7,dic8];
//类方法 传人参数是数组
[AFModel batchRequest:urls success:^(id json) {
//请求完成执行的操作
} faile:^{
//失败
}];
}
#pragma mark 以队列方式请求数据
+(void)batchRequest:(NSArray *)requestAry success:(void(^)(id json))success faile:(void(^)())fail{
//推荐好友3行
//推荐好友3行
//热门话题
//热门活动
//热门院校
//秘柚
//封面人物
//URL数组
NSArray *urlAry = @[[NSString stringWithFormat:@"%@%@",URL_ROOT212,URL_GETSUB],
[NSString stringWithFormat:@"%@%@",URL_ROOT212,URL_HY_SUB_3],
[NSString stringWithFormat:@"%@%@",URL_ROOT212,URL_HY_SUB_6],
[NSString stringWithFormat:@"%@%@",URL_ROOT212,URL_TOPIC],
[NSString stringWithFormat:@"%@%@",URL_ROOT212,URL_ACTIVITY],
[NSString stringWithFormat:@"%@%@",URL_ROOT212,URL_SCHOOL],
[NSString stringWithFormat:@"%@%@",URL_ROOT212,URL_MIYOU],
[NSString stringWithFormat:@"%@%@",URL_ROOT212,URL_FENGMIAN],
];
NSMutableArray *operationsAry = [NSMutableArray array];
for (int i = 0; i<requestAry.count; i++) {
NSString * str = @"";
if ([requestAry[i] count] > 0) {
for (NSString *key in [requestAry[i] allKeys]) {
//拼接参数
str = [str stringByAppendingFormat:@"&%@=%@",key,[requestAry[i] valueForKey:key]];
}
}
//post请求的参数必须是NSData类型
NSData *formData = [str dataUsingEncoding:NSUTF8StringEncoding];
//gitHub上ANF文档关于批量请求的request初始化如下
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlAry[i] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} error:nil];
[request addValue:[MD5_Sha1 returnBase64] forHTTPHeaderField:HTTPHEADER];
//加密
[request setHTTPBody:formData];
//operation初始化
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//讲请求添加到请求的数组 不是队列
[operationsAry addObject:operation];
}
//把请求的数组作为参数 调用AFN方法
NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:operationsAry progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
//请求进度
} completionBlock:^(NSArray *operations) {
NSMutableArray *resultAry = [NSMutableArray array];
//便利请求完成返回的数组
for(AFHTTPRequestOperation *operation in operations){
//判断非空
if (operation.responseObject==nil) {
NSLog(@"请求数据为空!~ ");
}
else{
// JSON化
NSMutableArray* json = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:NSJSONReadingMutableContainers error:nil];
[resultAry addObject:json];
}
}
//将值传回界面
success(resultAry);
NSLog(@"All operations in batch complete");
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
}