1.项目中引入AFNetwork,新建一个继承于NSObject的类Network,并在.h中定义一下方法:
//网络请求
- (void)networkWithURL:(NSString *)url
parameter:(NSDictionary *)paraDic
success:(void(^)(id obj))success
fail:(void(^)(NSError *error))fail;
//文件上传
- (void)networkWithURL:(NSString *)url
pic:(UIImage *)image
parameter:(NSDictionary *)paraDic
success:(void (^)(id obj))success
fail:(void (^)(NSError *error))fail;
//下载
//progressBlock 下载进度
//completeBlock 成功回调
- (void)downloadWithURL:(NSString *)url
progress:(void (^)(float percent))precentBlock
complete:(void (^)(NSString *fileName))completeBlock
fileUrl:(void(^)(NSURL *fileUrl))fileUrl;
2.定义方法后,在.m中首先实现网络请求功能
- (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];
}
3.文件上传功能,上传文件以图片为例
//图片以及其他信息上传
- (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 _Nonnull formData) {
//在这里提交图片/视频/音频文件
//把图片转为NSData
//第一个参数是 data
//第二个参数是服务器提供的字段名
//第三个字段随意
//第四个参数文件类型
NSData *data = UIImageJPEGRepresentation(image, 0.5);
[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];
}
4.下载功能
- (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];
}