1.创建操作管理者
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
//判断请求方式
if ([method isEqualToString:@"GET"]) {
//==============GET请求==============//
operation = [operationManager GET:url parameters:params success:^(AFHTTPRequestOperation*operation, id responseObject) {
block(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"GET请求网络失败:%@",error);
}];
}else if ([method isEqualToString:@"POST"]) {
//==============POST请求==============//
if (datas != nil) {
//———————————上传文件的POST请求————————————//
operation = [operationManager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//以时间格式作为图片名上传
NSDate *date = [NSDate date];
NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
[dataFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSString *fileDate = [dataFormatter stringFromDate:date];
//NSString *filename = [NSString stringWithFormat:@"%@.jpeg",fileDate];
NSString *filename = [NSString stringWithFormat:@"%@.mp4",fileDate];
//遍历需要上传的文件数据
for (NSString *name in datas) {
NSData *data = [datas objectForKey:name];
//[formData appendPartWithFileData:data name:name fileName:filename mimeType:@"image/jpeg"];
[formData appendPartWithFileData:data name:name fileName:filename mimeType:@"video/mp4"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
block(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"POST上传文件网络请求失败:%@",error);
}];
//上传进度
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long longtotalBytesExpectedToWrite) {
CGFloat progress = totalBytesWritten / (CGFloat)totalBytesExpectedToWrite;
NSLog(@"进度:%.1f",progress);
}];
}else {
[operationManager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, idresponseObject) {
block(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"POST网络请求失败:%@",error);
}];
}
}