AFN常用的方法目前只用到这些(get,post,上传,下载,网络判断),每次都要创建的话感觉很麻烦,所以根据以往的项目简单的封装了一下,创建了一个继承于NSObject的HHttpManager工具类,网络请求的话基本这些就够用了。本人对block理解也并不是很深,哪里有问题欢迎提出.
ps:这几天在接各种SDK,极光推送,融云聊天,QQ,微信,微博,支付宝,不得不说一句,看官方的开发文档真的心累,过几天我会把目前用到的融云聊天,QQ(登录,分享),微信(登录,分享,支付),支付宝,微博(登录,分享),各自像AFN一样封装成一个工具类,再接入的话,就负责设置白名单,初始化,openURL的回调,然后就用工具类直接调用自己封装的方法就好了,登录,分享,支付等都会在一个文件里,能省事不少,也给没有接过微信支付宝SDK的新手参考参考。敬请期待0.0
这里是AFNetworking的github链接
以下是AFN的封装,都是类方法,直接调用就好.
.h文件
#import
@interface HHttpManager : NSObject
//成功block 回调成功后得到的信息
typedef void (^HttpSuccess)(id responseObject);
//失败block 回调失败信息
typedef void (^HttpFailure)(NSError *error);
//状态block 回调网络状态字符串
typedef void (^StatusUnknown)(NSString *state);
typedef void (^StatusNoNetwork)(NSString *state);
typedef void (^StatusWiFi)(NSString *state);
typedef void (^Status2G_3G_4G)(NSString *state);
//进度block 回调网络下载/上传进度
typedef void (^HttpProgress)(CGFloat progressValue);
//成功block 回调成功后得到的信息
typedef void (^DownloadSuccess)(NSURL *filePath);
//失败block 回调失败信息
typedef void (^DownloadFailure)(NSError *error);
/**
GET数据请求
@param urlString URL字符串
@param success 成功回调
@param failure 失败回调
*/
+(void)GET:(NSString *)urlString success:(HttpSuccess)success failure:(HttpFailure)failure;
/**
GET数据请求
@param urlString URL字符串
@param parameters 字典参数
@param success 成功回调
@param failure 失败回调
*/
+(void)GET:(NSString *)urlString parameters:(NSDictionary *)parameters success:(HttpSuccess)success failure:(HttpFailure)failure;
/**
POST数据请求
@param urlString URL字符串
@param parameters 字典参数
@param success 成功回调
@param failure 失败回调
*/
+(void)POST:(NSString *)urlString parameters:(NSDictionary *)parameters success:(HttpSuccess)success failure:(HttpFailure)failure;
/**
单张或多张图片上传
@param urlString URL字符串
@param parameters 字典参数
@param imageArray 图片数组(这里是UIImage)
@param successs 成功回调
@param progress 进度回调
@param failure 失败回调
*/
+ (void)UPLOAD:(NSString *)urlString parameters:(id)parameters UploadImage:(NSMutableArray *)imageArray progressValue:(HttpProgress)progress success:(HttpSuccess)successs failure:(HttpFailure)failure;
/**
文件下载
@param urlString URL字符串
@param progress 进度回调
@param successs 成功回调(下载文件的最终地址)
@param failure 失败回调
*/
+ (void)DOWNLOAD:(NSString *)urlString progressValue:(HttpProgress)progress success:(DownloadSuccess)successs failure:(DownloadFailure)failure;
/**
实时监测网络变化(回调四种网络状态)
*/
+ (void)monitorNetworkStatusWiFi:(StatusWiFi)statusWiFi
Status2G_3G_4G:(Status2G_3G_4G)status2G_3G_4G
StatusNoNetwork:(StatusNoNetwork)statusNoNetwork
StatusUnknown:(StatusUnknown)statusUnknown;
@end
.m文件
#import "HHttpManager.h"
#import "AFNetworking.h"
@implementation HHttpManager
//GET请求
+(void)GET:(NSString *)urlString success:(HttpSuccess)success failure:(HttpFailure)failure{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
manager.requestSerializer.timeoutInterval = 10.f;
[manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
[manager GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//数据请求的进度
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if(success){
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(failure){
failure(error);
}
}];
}
+(void)GET:(NSString *)urlString parameters:(NSDictionary *)parameters success:(HttpSuccess)success failure:(HttpFailure)failure{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
manager.requestSerializer.timeoutInterval = 10.f;
[manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
[manager GET:urlString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
//数据请求的进度
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if(success){
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(failure){
failure(error);
}
}];
}
//POST请求
+(void)POST:(NSString *)urlString parameters:(NSDictionary *)parameters success:(HttpSuccess)success failure:(HttpFailure)failure{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
manager.requestSerializer.timeoutInterval = 10.f;
[manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
[manager POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
//数据请求的进度
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if(success){
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(failure){
failure(error);
}
}];
}
// 上传
+ (void)UPLOAD:(NSString *)urlString parameters:(id)parameters UploadImage:(NSMutableArray *)imageArray progressValue:(HttpProgress)progress success:(HttpSuccess)successs failure:(HttpFailure)failure{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:urlString parameters:parameters constructingBodyWithBlock:^(id formData) {
for (UIImage *image in imageArray) {
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
NSData *data = UIImageJPEGRepresentation(image, 0.7);
[formData appendPartWithFileData:data name:@"uploadimage" fileName:fileName mimeType:@"image/png"];
}
}progress:^(NSProgress * _Nonnull uploadProgress) {
if(progress){
progress(1.0 * uploadProgress.completedUnitCount/uploadProgress.totalUnitCount);
}
}success:^(NSURLSessionDataTask *task, id responseObject) {
if (successs) {
successs(responseObject);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
if (failure) {
failure(error);
}
}];
}
// 下载
+ (void)DOWNLOAD:(NSString *)urlString progressValue:(HttpProgress)progress success:(DownloadSuccess)successs failure:(DownloadFailure)failure{
AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
if(progress){
progress(1.0 * downloadProgress.completedUnitCount/downloadProgress.totalUnitCount);
}
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
NSLog(@"targetPath:%@",targetPath);
NSLog(@"fullPath:%@",fullPath);
return [NSURL fileURLWithPath:fullPath];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
if (!error) {
if (successs) {
NSLog(@"%@",filePath);
successs(filePath);
}
}else{
if (failure) {
failure(error);
}
}
}];
//3.执行Task
[download resume];
}
// 网络监测
+ (void)monitorNetworkStatusWiFi:(StatusWiFi)statusWiFi
Status2G_3G_4G:(Status2G_3G_4G)status2G_3G_4G
StatusNoNetwork:(StatusNoNetwork)statusNoNetwork
StatusUnknown:(StatusUnknown)statusUnknown{
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
if (statusUnknown) {
statusUnknown(@"未知网络");
}
break;
case AFNetworkReachabilityStatusNotReachable:
if (statusNoNetwork) {
statusNoNetwork(@"无网络连接");
}
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
if (statusWiFi) {
statusWiFi(@"wifi");
}
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
if (status2G_3G_4G) {
status2G_3G_4G(@"蜂窝流量");
}
break;
default:
break;
}
}];
[manager startMonitoring];
}
@end