git下载地址:https://github.com/AFNetworking/AFNetworking
get请求
#import <AFNetworking.h>
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];//这句话最好加上
[manager GET:@"请求链接" parameters:@"参数组" progress:^(NSProgress * _Nonnull downloadProgress) {
//请求进度
}success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//请求成功
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];//把NSData转换成字典类型
}failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//请求失败
}];
post请求
#import <AFNetworking.h>
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:@"请求链接" parameters:@"参数组" progress:^(NSProgress * _Nonnull uploadProgress) {
//请求进度
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//请求成功
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//请求失败
}];
文件下载
#import <AFNetworking.h>
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//下载任务
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:@"请求链接" progress:^(NSProgress * _Nonnull downloadProgress) {
//加载进度
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//下载存放地址,要返回存放地址(存放地址前面加file://)
return nil;
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
// 下载完成之后,解压缩文件
}];
[task resume];
文件上传
#import <AFNetworking.h>
//创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:@"请求链接" parameters:@"参数组" constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//上传文件参数,dataArray是一个NSData数组
if (dataArray.count > 0) {
for (NSData *imageData in dataArray) {
[formData appendPartWithFileData:imageData name:dataKey fileName:dataName mimeType:@"image/png"];
}
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
//上传进度
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//请求成功(返回的是NSData类型的数据)
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//请求失败
}];
网友评论