AFNetworking以及NSURLSession网络封装

此文章转载自 http://www.cnblogs.com/linxiu-0925/p/5379698.html
一、AFNetworking
首先要导入AFNetworking包
然后定义两个文件继承NSObject。
VPKCResponse.h
VPKCResponse.m
VPKCRequestManager.h
VPKCRequestManager.m

VPKCResponse.h文件:

#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, VPKCHttpStatusCode) {
    
    /// 业务正常处理
    VPKCStatusCode_OK = 200,
    
    /// 袋鼠家业务错误,返回错误码和错误信息
    VPKCStatusCode_Accepted = 202,
    
    /// 上行参数不符合定义,比较必须参数、json格式、数据类型等
    VPKCStatusCode_BadRequest = 400,
    
    /// 权限不够,hmac问题
    VPKCStatusCode_Unauthorized = 401,
    
    /// 请求的uri不符合协议规定,在服务器无法找到对应的处理器
    VPKCStatusCode_NotFound = 404,
    
    /// 服务器异常
    VPKCStatusCode_InternalServerError = 500,
    
    /// 接口对应的服务未部署
    VPKCStatusCode_BadGateway = 502,
    
};
@interface VPKCResponse : NSObject
/// 请求返回 responseObject
@property(copy, nonatomic) id responseObject;
//
/// 请求头信息
@property (copy, nonatomic) id headerFields;
//
/// AFNetworking返回错误信息
@property(strong, nonatomic) NSError *error;
//
//
///// 服务器状态码
@property (strong, nonatomic) NSNumber *status;

///// 202状态错误码
@property (strong, nonatomic) NSNumber *errorCode;
//
///// 202状态错误描述信息
@property (copy, nonatomic) NSString *errorDescription;
//
///// 弹框显示内容
@property (nonatomic, copy) NSString *content;
@end

VPKCRequestManager.h文件

#import <Foundation/Foundation.h>
#import "VPKCResponse.h"
@interface VPKCRequestManager : NSObject
/// 获取当前网络是否可用
@property (assign, nonatomic, readonly) BOOL reachable;

/// 单利
+ (VPKCRequestManager *)sharedRequest;

/// 取消当前请求任务
- (void)cancelCurrentTask;

/// 取消所有请求任务
- (void)cancelAllTask;


/// GET
+ (VPKCRequestManager *)GET:(NSString *)url
                 withParame:(NSDictionary *)parame
               withComplete:(void(^)(VPKCResponse *responseObj))result;


/// POST
+ (VPKCRequestManager *)POST:(NSString *)url
                  withParame:(NSDictionary *)parame
                withComplete:(void(^)(VPKCResponse *responseObj))result;

/// PUT
+ (VPKCRequestManager *)PUT:(NSString *)url
                 withParame:(NSDictionary *)parame
               withComplete:(void(^)(VPKCResponse *responseObj))result;


/// PATCH
+ (VPKCRequestManager *)PATCH:(NSString *)url
                   withParame:(NSDictionary *)parame
                 withComplete:(void(^)(VPKCResponse *responseObj))result;

/// DELETE
+ (VPKCRequestManager *)DELETE:(NSString *)url
                    withParame:(NSDictionary *)parame
                  withComplete:(void(^)(VPKCResponse *responseObj))result;
@end


VPKCRequestManager.m文件

#import "VPKCRequestManager.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "AFNetworking.h"


typedef NS_ENUM(NSInteger , VPKCRequestMethod) {
    VPKCRequestMethodGet,
    VPKCRequestMethodPost,
    VPKCRequestMethodPut,
    VPKCRequestMethodDelete,
    VPKCRequestMethodPatch,
    VPKCRequestMethodHead,
};

const NSString *methodStirng[] = {
    [VPKCRequestMethodGet] = @"GET",
    [VPKCRequestMethodPost] = @"POST",
    [VPKCRequestMethodHead] = @"HEAD",
    [VPKCRequestMethodPut] = @"PUT",
    [VPKCRequestMethodDelete] = @"DELETE",
    [VPKCRequestMethodPatch] = @"PATCH",
};
@interface VPKCRequestManager()
@property (strong, nonatomic) AFHTTPSessionManager *sessionManager;
@property (strong, nonatomic) NSURLSessionDataTask *sessionDataTask;

/// 网络是否可用
@property (assign, nonatomic, readwrite) BOOL reachable;
//
/// 当前任务ID
@property (assign, nonatomic) NSInteger taskIdentifier;
//
//
//
/// 请求地址(前半段)
@property (strong, nonatomic) NSString *requestBaseUrl;
// 请求地址(后半段)
@property (copy, nonatomic) NSString *requestApiUrl;
/// 请求参数
@property (strong, nonatomic) NSDictionary *requestParame;
/// 请求方式
@property (assign, nonatomic) VPKCRequestMethod requestMethod;

@end
@implementation VPKCRequestManager
+ (VPKCRequestManager *)sharedRequest {
    static VPKCRequestManager *requestManage;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        requestManage = [[self alloc] initPrivate];
    });
    
    return requestManage;
}

/// GET
+ (VPKCRequestManager *)GET:(NSString *)url
                 withParame:(NSDictionary *)parame
               withComplete:(void(^)(VPKCResponse *responseObj))result {
    
    return [self requestConfigWithUrl:url withParame:parame withMethod:VPKCRequestMethodGet withComplete:result];
}


/// POST
+ (VPKCRequestManager *)POST:(NSString *)url
                  withParame:(NSDictionary *)parame
                withComplete:(void(^)(VPKCResponse *responseObj))result {
    return [self requestConfigWithUrl:url withParame:parame withMethod:VPKCRequestMethodPost withComplete:result];
}

/// PUT
+ (VPKCRequestManager *)PUT:(NSString *)url
                 withParame:(NSDictionary *)parame
               withComplete:(void(^)(VPKCResponse *responseObj))result {
    return [self requestConfigWithUrl:url withParame:parame withMethod:VPKCRequestMethodPut withComplete:result];
}


/// PATCH
+ (VPKCRequestManager *)PATCH:(NSString *)url
                   withParame:(NSDictionary *)parame
                 withComplete:(void(^)(VPKCResponse *responseObj))result {
    return [self requestConfigWithUrl:url withParame:parame withMethod:VPKCRequestMethodPatch withComplete:result];
}

/// DELETE
+ (VPKCRequestManager *)DELETE:(NSString *)url
                    withParame:(NSDictionary *)parame
                  withComplete:(void(^)(VPKCResponse *responseObj))result {
    return [self requestConfigWithUrl:url withParame:parame withMethod:VPKCRequestMethodDelete withComplete:result];
}


/// 取消当前请求任务
- (void)cancelCurrentTask {
    
    // cancel specific task
    for (NSURLSessionDataTask* task in [_sessionManager tasks]) {
        if (task.taskIdentifier == _taskIdentifier) {
            [task cancel];
        }
    }
}

/// 取消所有请求任务
- (void)cancelAllTask {
    [_sessionDataTask cancel];
}



- (instancetype)initPrivate {
    if (self = [super init]) {
        
        _reachable = YES;
        _requestBaseUrl = [NSURL URLWithString:@"http://baidu.com"];
        _requestMethod = VPKCRequestMethodGet;
        _sessionManager = [AFHTTPSessionManager manager];
        _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        _sessionManager.requestSerializer.timeoutInterval = 30;
        _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"text/plain", nil];
        [_sessionManager setSecurityPolicy:[self customSecurityPolicy]];
        
        [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
        [_sessionManager.reachabilityManager startMonitoring];
        __weak typeof(self)weakSelf = self;
        [_sessionManager.reachabilityManager setReachabilityStatusChangeBlock:^void(AFNetworkReachabilityStatus status)
         {
             weakSelf.reachable = [@(status) boolValue];
         }];
        
    }
    return self;
}
//// 设置请求头
- (void)setHmacStringWithSessionManager:(AFHTTPRequestSerializer *)requestSerializer {
    
    //    NSString *time = [VPKCUtils timeToTurnTheTimestamp];
    //    NSString *hmac = [NSString stringWithFormat:@"%@\n%@/%@\n%@",time,kHmacUrl,_requestApiUrl,methodStirng[_requestMethod]];
    //    hmac = [NSString hmac:hmac];
    //    NSString *devID = [VPKCUserInfo sharedUserInfo].parentDeviceId;
    //    NSString *user = [VPKCUserInfo sharedUserInfo].username;
    //    NSString *child = [VPKCUserInfo sharedUserInfo].childDeviceId?:@"";
    //
    //    [requestSerializer setValue:time forHTTPHeaderField:@"X-KC-TIME"];
    //    [requestSerializer setValue:hmac forHTTPHeaderField:@"X-KC-HMAC"];
    //    [requestSerializer setValue:devID forHTTPHeaderField:@"X-KC-DEVICEID"];
    //    [requestSerializer setValue:user forHTTPHeaderField:@"X-KC-USERNAME"];
    //    [requestSerializer setValue:child forHTTPHeaderField:@"X-KC-CHILD-DEVICEID"];
}
// https配置
- (AFSecurityPolicy*)customSecurityPolicy {
    
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"d" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    [securityPolicy setAllowInvalidCertificates:NO];
    [securityPolicy setPinnedCertificates:@[certData]];
    return securityPolicy;
}
//
/// 拼接url
- (NSString *)requestServiceUrlString {
    if ([_requestApiUrl hasPrefix:@"http"]) {
        return _requestApiUrl;
    }
    return [NSString stringWithFormat:@"%@/%@",_requestBaseUrl,_requestApiUrl];
}

#pragma mark ------------------------------------------------------------

- (void)requestStartWithWithSuccess:(void (^)(VPKCResponse *))result {
    
    
    [self requestMethodWithSuccess:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"【request_responseObject】=%@ == %@",responseObject,task.response.URL.absoluteString);
        VPKCResponse *response = [[VPKCResponse alloc] init];
        response.responseObject = responseObject;
        response.error = nil;
        
        if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSHTTPURLResponse *r = (NSHTTPURLResponse *)task.response;
            response.headerFields = r.allHeaderFields;
            response.status = @(r.statusCode);
        }
        if (result) {
            result(response);
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"【request_error】=%@  == Url = %@",error,task.response.URL.absoluteString);
        VPKCResponse *response = [[VPKCResponse alloc] init];
        response.error = error;
        if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSHTTPURLResponse *r = (NSHTTPURLResponse *)task.response;
            response.headerFields = r.allHeaderFields;
            response.status = @(r.statusCode);
            if ([response.status isEqualToNumber:@403]) {
                NSData *data = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
                if (data) {
                    NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    NSDictionary *responseObject = [VPKCUtils jsonWithString:s];
                    NSLog(@"error = %@",responseObject);
                    response.content = responseObject[@"content"];
                    response.errorCode = responseObject[@"errorCode"];
                    response.errorDescription = responseObject[@"errorDescription"];
                }
            }
            
            if ([response.status isEqualToNumber:@502]) {
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"连接服务器异常" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [alertView show];
            }
        }
        if (result) {
            result(response);
        }
    }];
    
}


- (void)requestMethodWithSuccess:(void(^)(NSURLSessionDataTask *task, id responseObject))success failure:(void(^)(NSURLSessionDataTask * task, NSError * error))failure {
    
    if (!_reachable) {
        failure(nil,[NSError errorWithDomain:@"网络连接失败" code:-1 userInfo:nil]);
        return ;
    }
    
    NSDictionary *parame = _requestParame;
    NSString *URLString = [self requestServiceUrlString];
    [self setHmacStringWithSessionManager:_sessionManager.requestSerializer];
    
    NSLog(@"【URL】%@",URLString);
    NSLog(@"【parame】%@",parame);
    
    
    
    switch (_requestMethod)
    {
        case VPKCRequestMethodGet:
            _sessionDataTask = [_sessionManager GET:URLString parameters:parame success:success failure:failure];
            break;
        case VPKCRequestMethodPost:
            _sessionDataTask = [_sessionManager POST:URLString parameters:parame success:success failure:failure];
            break;
        case VPKCRequestMethodPut:
            _sessionDataTask =  [_sessionManager PUT:URLString parameters:parame success:success failure:failure];
            break;
        case VPKCRequestMethodDelete:
            _sessionDataTask =  [_sessionManager DELETE:URLString parameters:parame success:success failure:failure];
            break;
        case VPKCRequestMethodPatch:
            _sessionDataTask =  [_sessionManager PATCH:URLString parameters:parame success:success failure:failure];
            break;
        case VPKCRequestMethodHead:{
            _sessionDataTask = [_sessionManager HEAD:URLString parameters:parame success:^(NSURLSessionDataTask * task) {
                success(task,nil);
            } failure:failure];
        }
            break;
        default:
            break;
    }
    _taskIdentifier = _sessionDataTask.taskIdentifier;
}


+ (VPKCRequestManager *)requestConfigWithUrl:(NSString *)url
                                  withParame:(NSDictionary *)parame
                                  withMethod:(VPKCRequestMethod)method
                                withComplete:(void(^)(VPKCResponse *responseObj))result
{
    VPKCRequestManager *request = [VPKCRequestManager sharedRequest];
    request.requestApiUrl = url;
    request.requestParame = parame;
    request.requestMethod = method;
    [request requestStartWithWithSuccess:result];
    return request;
}
/**
 *  将字符串转化为字典
 *
 *  @param string JSON字符串
 *
 *  @return 字典
 */

//+ (NSDictionary *)jsonWithString:(NSString *)string;

+ (NSDictionary *)jsonWithString:(NSString *)string {
    
    if (!string) {
        return nil;
    }
    NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    
    if (err) {
        return nil;
    }
    return dic;
}

二、NSURLSession
这里就简单封装以下get和post请求
get请求

+ (void)getWithUrlString:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock
{
    NSMutableString *mutableUrl = [[NSMutableString alloc] initWithString:url];
    if ([parameters allKeys]) {
        [mutableUrl appendString:@"?"];
        for (id key in parameters) {
            NSString *value = [[parameters objectForKey:key] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            [mutableUrl appendString:[NSString stringWithFormat:@"%@=%@&", key, value]];
        }
    }
    NSString *urlEnCode = [[mutableUrl substringToIndex:mutableUrl.length - 1] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlEnCode]];
    NSURLSession *urlSession = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            failureBlock(error);
        } else {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            successBlock(dic);
        }
    }];
    [dataTask resume];
}

post请求:

+ (void)postWithUrlString:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock
{
    NSURL *nsurl = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl];
    //如果想要设置网络超时的时间的话,可以使用下面的方法:
    //NSMutableURLRequest *mutableRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //设置请求类型
    request.HTTPMethod = @"POST";
    //把参数放到请求体内
    request.HTTPBody =  [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil ];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) { //请求失败
            failureBlock(error);
        } else {  //请求成功
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            successBlock(dic);
        }
    }];
    [dataTask resume];  //开始请求
}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,125评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,293评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,054评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,077评论 1 291
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,096评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,062评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,988评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,817评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,266评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,486评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,646评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,375评论 5 342
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,974评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,621评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,796评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,642评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,538评论 2 352

推荐阅读更多精彩内容

  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 3,657评论 2 7
  • 218.241.181.202 wxhl60 123456 192.168.10.253 wxhl66 wxhl6...
    CYC666阅读 1,380评论 0 6
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,090评论 4 62
  • 有几个人能坚持看完全文了? 技术 向沙宣看齐 好多人都希望能向沙宣看齐,这是一个好现象,证明我们中国已经拥有一部分...
    简明估阅读 616评论 0 1
  • 行动起来把自己拖延几天的事办完,感觉好轻松,看到好几次伙伴们发表这段话,我以前认为快,只是快过别人,而最终了解,真...
    melody静阅读 165评论 0 0