創(chuàng)建請求對象
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"];
發(fā)起請求铸题,比如post請求盖溺,調(diào)用方法:
- (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;
上傳文件調(diào)用方法
- (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];