创建请求对象
self.httpUrlSessionManager = [[AFHTTPSessionManager alloc] init];
[self.httpUrlSessionManager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
self.httpJsonSessionManager = [[AFHTTPSessionManager alloc] init];
self.httpJsonSessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
[self.httpJsonSessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
发起请求,比如post请求,调用方法:
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
上传文件调用方法
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
如:
[self.httpUrlSessionManager POST:finalUrl parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
[formData appendPartWithFileData:fileData name:@"name" fileName:fileName mimeType:@""];
} progress:^(NSProgress * _Nonnull uploadProgress) {
if (ccuploadProgress) {
ccuploadProgress((CGFloat)uploadProgress.completedUnitCount/(CGFloat)uploadProgress.totalUnitCount);
}
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (error && failure) {
failure(error);
}
}];
下载文件:
NSURL *url=[NSURL URLWithString:urlstring];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
NSURLSessionDownloadTask *task= [mgr downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
if (cdownloadProgress) {
cdownloadProgress((CGFloat)downloadProgress.completedUnitCount/(CGFloat)downloadProgress.totalUnitCount);
}
}destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
return [NSURL fileURLWithPath:filePath isDirectory:NO];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
if(error){
failure(error);
}else{
success(nil);
}
}];
[task resume];