OC下的网络请求,大家都会第一时间想到AFNetworking,下面给大家简单介绍一下AFNetWork的使用。
首先,通过pod的方式引入AFNetwork,新建一个network的类,继承NSObject,并引入AFNetwork相关的头文件。接下来演示一下如果使用AFNetwork来实现网络请求,文件上传,下载这些基本的功能。
1.1 网络请求 ing
- (void)networkWithURL:(NSString *)url parameter:(NSDictionary *)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail {
//NSURLSession 配置信息
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//创建请求
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:paraDic constructingBodyWithBlock:nil error:nil];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
fail(error);
} else {
success(responseObject);
}
}];
//开启任务
[dataTask resume];
}
1.2文件上传
(void)networkWithURL:(NSString *)url pic:(UIImage *)image parameter:(NSDictionary *)paraDic success:(void (^)(id obj))success fail:(void (^)(NSError *error))fail {
//NSURLSession 配置信息
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//创建请求
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:paraDic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//在这里提交图片/视频/音频文件
//把图片转为NSData
//第一个参数是 data
//第二个参数是服务器提供的字段名
//第三个字段随意
//第四个参数文件类型
NSData *data = UIImageJPEGRepresentation(image, 0.5); //图片的引用和压缩系数,文件的数据格式,比UIImagePNGRepresentation返回的图片的大小要小很多
[formData appendPartWithFileData:data name:@"iconfile" fileName:[NSString stringWithFormat:@"%f.png", [[NSDate date] timeIntervalSince1970]] mimeType:@"PNG/JPEG/JPG"];
} error:nil];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
fail(error);
} else {
success(responseObject);
}
}];
//开启任务
[dataTask resume];
}
1.3 下载文件
- (void)downloadWithURL:(NSString *)url
progress:(void (^)(float percent))precentBlock
complete:(void (^)(NSString *fileName))completeBlock
fileUrl:(void(^)(NSURL *fileUrl))fileUrl {
//在cache文件下, 创建存储MP3文件的的文件夹
//建立存储路径/Download
NSString *mp3FilePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"Download"];
//判断文件夹是否存在,不存在就创建对应路劲下的文件夹
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:mp3FilePath]) {
} else {
//创建文件夹
[fileManager createDirectoryAtPath:mp3FilePath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString *fileName = url.md5;
//文件下载成功后存储路径
NSString *filePath = [mp3FilePath stringByAppendingPathComponent:fileName];
//如果文件已下载, 停止下载
if ([fileManager fileExistsAtPath:filePath]) {
[[[UIAlertView alloc] initWithTitle:@"提示" message:@"文件已下载" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
return;
}
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//创建request
//POST请求, 用 [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:]
//如果是GET请求, 用下面的方法
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
//创建下载任务
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//这里返回下载进度
dispatch_async(dispatch_get_main_queue(), ^{
precentBlock(downloadProgress.completedUnitCount / (downloadProgress.totalUnitCount / 1.0));
});
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//要求返回文件存储的路径
//临时文件
NSString *tempPath = NSTemporaryDirectory();
return [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", tempPath, fileName]];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePt, NSError * _Nullable error) {
//下载完成
if (!error) {
//先把临时文件移到download文件夹
//然后删除临时文件
//成功回调
[fileManager copyItemAtURL:filePt toURL:[NSURL fileURLWithPath:filePath] error:nil];
[fileManager removeItemAtURL:filePt error:nil];
completeBlock(fileName);
} else {
NSLog(@"网络请求失败");
}
}];
[task resume];
}
1.4 网络监听
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
//当网络状态发生改变的时候,会通过block回调告诉我
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
// AFNetworkReachabilityStatusUnknown = -1, 未知
// AFNetworkReachabilityStatusNotReachable = 0,无网络
// AFNetworkReachabilityStatusReachableViaWWAN = 1,蜂窝数据
// AFNetworkReachabilityStatusReachableViaWiFi = 2,wifi
switch (status) {
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"wifi");
break;
case AFNetworkReachabilityStatusUnknown:
NSLog(@"Unknown");
break;
default:
break;
}
}];
//开启监控
[manager startMonitoring];
注意事项
AFNetworking版本兼容性问题,可能由于AFNetworking版本问题,AFNetworking封装的接口会发生变化,比如参数的个数,函数的名称的等,当多方开发时一定要注意统一版本。
- (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;
新版的AFNetworking会比旧版本的多了一个header:参数,导致兼容性问题。