AFHTTPRequestOperationManager的底层使用了NSOperation,并且使用的是NSURLConnection,可支持iOS6及更新的系统版本;AFURLSessionManager使用的是更新的NSURLSession,支持iOS7.0以上系统。本人强烈建议使用AFURLSessionManager除非你要使用operations或者需要支持iOS6。3.0的AFNetowrking使用AFHttpSessionManager代替AFHTTPRequestOperationManager,请注意!
下面来写一下AFURLSessionManager的上传图片方法:
//上传图片 - (void)requestUploadPhotoWithImage:(UIImage *)image withSucess:(HLSucessBlock)success failure:(HLFailureBlock)failure { NSData *imagedata = UIImageJPEGRepresentation(image, 0.7f); NSString *urlString = [NSString stringWithFormat:@"%@%@",HLNETWORK_BASE_URL_TEST,kUrl_UploadImages]; urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSMutableDictionary *params = [NSMutableDictionary dictionary]; NSString *token = [HLFitmentManager instance].userInfo.token; if (CHECK_VALID_STRING(token)) { [params setObject:token forKey:@"token"]; } NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"yyyyMMddHHmmss"; NSString *str = [formatter stringFromDate:[NSDate date]]; NSString *fileName = [NSString stringWithFormat:@"%@.jpg",str]; [formData appendPartWithFileData:imagedata name:@"image" fileName:fileName mimeType:@"image/jpeg"]; } error:nil]; AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; manager.responseSerializer = [AFJSONResponseSerializer serializer]; NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) { //进度 } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { HLParser *parser = [[HLParser alloc] init]; BOOL isError = [parser hasErrorWithDict:responseObject]; if (isError) { //上传图片失败 NSLog(@"上传图片失败"); failure(nil,parser.error); }else { NSLog(@"上传图片成功"); success(nil,responseObject); } }]; [uploadTask resume]; }