标签:
封装网络请求类便捷, 适合多个地方使用.
第一封装下载方法
前提用Cocoapods或者直接引用第三方AFNetWorking
定义一个类NetWorkingManager, 继承于NSObject
A: 在.h中写方法声明
#import <Foundation/Foundation.h>
@interface NetWorkManager : NSObject
- (void)downLoadWithUrl:(NSString *)url progress:(void(^)(float progress))progressBlock complete:(void(^)(NSString *filePath))completeBlock;
//其中有两个Block块回调方法, 第一个回调下载进度, 第二个回调下载完成后返回文件路径名
@end
B: 在.m中写方法实现
#import "NetWorkManager.h"
#import "NSString+Security.h"
#import <AFNetworking/AFNetworking.h>
@implementation NetWorkManager
- (void)downLoadWithUrl:(NSString *)url progress:(void (^)(float))progressBlock complete:(void (^)(NSString *))completeBlock{
//在cache文件下, 创建存储MP3文件的文件夹
//创建文件夹路径
NSString *mp3Path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject] stringByAppendingPathComponent:@"downLoad"];
NSLog(@"%@", mp3Path);
NSFileManager *fileManager = [NSFileManager defaultManager];
//判断文件路径是否存在, 不存在就创建, 存在了就不创建
if ([fileManager fileExistsAtPath:mp3Path]) {
}else{
[fileManager createDirectoryAtPath:mp3Path withIntermediateDirectories:YES attributes:nil error:nil];
}
//对下载的文件名进行加密
NSString *fileName = url.md5;
//创建文件存储路径
NSString *filePath = [mp3Path stringByAppendingPathComponent:fileName];
//判断文件名是否存在, 存在就说明已经下载过了, 不再下载, 反之就下载文件
if ([fileManager fileExistsAtPath:filePath]) {
return;
}
//文件下载
//创建 manager
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//POST请求 用[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod
//创建 request;适用于GET请求
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
//创建下载任务
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//返回下载进度
progressBlock(downloadProgress.completedUnitCount / (downloadProgress.totalUnitCount / 1.0));
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//返回文件存储路径
return [NSURL fileURLWithPath:filePath];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//下载完成
completeBlock(mp3Path);
}];
[task resume];
}
@end
第二封装POST网络请求
A:在.h中写方法的声明
//封装POST网络请求
//parameter 请求体
- (void)networkWithUrl:(NSString *)Url parameter:(NSDictionary *)dic success:(void(^)(id obj))successBlock fail:(void(^)(NSError *error))failBlock;
//两个回调方法, 第一个回调成功后的操作, 第二个回调失败信息
B: 在.m中写方法实现
- (void)networkWithUrl:(NSString *)Url parameter:(NSDictionary *)dic success:(void (^)(id))successBlock fail:(void (^)(NSError *))failBlock{
//创建Session manager
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//创建request, POST请求方法
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:Url parameters:dic constructingBodyWithBlock:nil error:nil];
//创建请求任务
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
failBlock(error);
}else{
successBlock(responseObject);
}
}];
//开启任务
[task resume];
}
注意:需要在AFNetworking第三方里的
文件的第226行添加
字段
第三封装上传图片方法
A:在.h中写方法的声明
//封装上传图片方法
- (void)netWorkWithURL:(NSString *)url pic:(UIImage *)image parameter:(NSDictionary *)dic successBlock:(void (^)(id obj))success failBlock:(void (^)(NSError *error))fail;
B:在.m中写方法的实现
- (void)netWorkWithURL:(NSString *)url pic:(UIImage *)image parameter:(NSDictionary *)dic successBlock:(void (^)(id))success failBlock:(void (^)(NSError *))fail{
//创建sessionManager
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//创建request, POST请求
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//在这里提交图片/视频/音频等数据
//先把图片转为 NSData
//参数2:缩放比例
NSData *data = UIImageJPEGRepresentation(image, 0.5);
//参数1:是data数据
//参数2:服务器提供的字段名, 片刻里面叫 iconfile
//参数3:随意填写
//参数4:文件类型
[formData appendPartWithFileData:data name:@"iconfile" fileName:[NSString stringWithFormat:@"%f.png", [[NSDate date] timeIntervalSince1970]] mimeType:@"PNG/JPEG/JPG"];
} error:nil];
//创建请求任务
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
fail(error);
}else{
success(responseObject);
}
}];
[task resume];
}
注意:此方法一般会用在注册中, 因为注册时需要用户选择头像上传到服务器上, 一般的网络请求不满足需求.
标签:
原文地址:http://www.cnblogs.com/YhhMzl/p/5138029.html