封装网络请求类便捷, 适合多个地方使用.
第一封装下载方法
前提用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文件的文件夹
//cache文件夹路径
NSString *mp3Fith = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject] stringByAppendingPathComponent:@"downLoad"];
//判断文件夹是否存在
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:mp3Fith]) {
}else{
//不存在就创建文件夹
[fileManager createDirectoryAtPath:mp3Fith withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString *fileName = url.md5;
//文件下载成功后的存储路径
NSString *filePath = [mp3Fith stringByAppendingPathComponent:fileName];
//判断MP3文件是否存在, 存在就不要再次下载
//如果下载后的文件存在, 就不再下载
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) {
//这里面返回的是下载进度
//放到主线程中, UI控件刷新必须放在主线程中, 为了让button上的title时刻显示下载进度
dispatch_async(dispatch_get_main_queue(), ^{
progressBlock(downloadProgress.completedUnitCount / (downloadProgress.totalUnitCount / 1.0));
});
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//要求返回文件存储路径
//缓存路径, 临时文件
//下载成功了, 把下载的文件拷到filePath路径里
NSString *tempPath = NSTemporaryDirectory();
return [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", tempPath, fileName]];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable fileP, NSError * _Nullable error) {
//下载完成
if (!error) {
//先把临时文件移到 download 文件夹里
//然后删除临时文件
//成功回调
//拷贝
[fileManager copyItemAtURL:fileP toURL:[NSURL fileURLWithPath:filePath] error:nil];
//删除临时文件
[fileManager removeItemAtURL:fileP error:nil];
completeBlock(fileName);
}else{
NSLog(@"网络请求失败");
}
}];
//开启任务
[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];
}
注意:此方法一般会用在注册中, 因为注册时需要用户选择头像上传到服务器上, 一般的网络请求不满足需求.
第四封装带缓存的 网络请求
A:在.h中写方法的声明
//封装缓存
- (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{
//创建sessionManager
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:dic constructingBodyWithBlock:nil error:nil];
//缓存文件储存路径
NSString *cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject] stringByAppendingPathComponent:@"cacheData"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:cachePath]) {
}else{
[fileManager createDirectoryAtPath:cachePath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSString *cacheFile = [cachePath stringByAppendingPathComponent:url.md5];
//如果有error 请求失败
//反之 ,成功
if (error) {
//从缓存路径下取出数据
id obj = [[NSDictionary alloc] initWithContentsOfFile:cacheFile];
if (obj) {
successBlock(obj[@"data"]);
}else{
failBlock(error);
}
failBlock(error);
}else{
//先存到本地文件夹下
//再成功回调
[@{@"data":responseObject} writeToFile:cacheFile atomically:YES];
successBlock(responseObject);
}
}];
[task resume];
}