IOS開發(fā)之—— 在AFN基礎(chǔ)上進(jìn)行的網(wǎng)絡(luò)請(qǐng)求的封裝

網(wǎng)絡(luò)請(qǐng)求的思路:如果請(qǐng)求成功的話AFN的responseObject就是解析好的兴枯。1發(fā)送網(wǎng)絡(luò)請(qǐng)求浦妄;get/post/或者別的 帶上URL,需要傳的參數(shù)2判斷后臺(tái)網(wǎng)絡(luò)狀態(tài)碼有沒有請(qǐng)求成功;3 請(qǐng)求成功:解析數(shù)據(jù)踏施,刷新頁面4請(qǐng)求失敗做處理VPKCResponse.hVPKCResponse.mVPKCRequestManager.hVPKCRequestManager.m定義兩個(gè)文件繼承NSObject。VPKCResponse.h#importtypedef NS_ENUM(NSInteger, VPKCHttpStatusCode) {? ? ? ? /// 業(yè)務(wù)正常處理? ? VPKCStatusCode_OK = 200,? ? ? ? /// 袋鼠家業(yè)務(wù)錯(cuò)誤喧锦,返回錯(cuò)誤碼和錯(cuò)誤信息? ? VPKCStatusCode_Accepted = 202,? ? ? ? /// 上行參數(shù)不符合定義读规,比較必須參數(shù)、json格式燃少、數(shù)據(jù)類型等? ? VPKCStatusCode_BadRequest = 400,? ? ? ? /// 權(quán)限不夠束亏,hmac問題? ? VPKCStatusCode_Unauthorized = 401,? ? ? ? /// 請(qǐng)求的uri不符合協(xié)議規(guī)定,在服務(wù)器無法找到對(duì)應(yīng)的處理器? ? VPKCStatusCode_NotFound = 404,? ? ? ? /// 服務(wù)器異常? ? VPKCStatusCode_InternalServerError = 500,? ? ? ? /// 接口對(duì)應(yīng)的服務(wù)未部署? ? VPKCStatusCode_BadGateway = 502,};@interface VPKCResponse : NSObject/// 請(qǐng)求返回 responseObject@property(copy, nonatomic) id responseObject;///// 請(qǐng)求頭信息@property (copy, nonatomic) id headerFields;///// AFNetworking返回錯(cuò)誤信息@property(strong, nonatomic) NSError *error;///////// 服務(wù)器狀態(tài)碼@property (strong, nonatomic) NSNumber *status;///// 202狀態(tài)錯(cuò)誤碼@property (strong, nonatomic) NSNumber *errorCode;/////// 202狀態(tài)錯(cuò)誤描述信息@property (copy, nonatomic) NSString *errorDescription;/////// 彈框顯示內(nèi)容@property (nonatomic, copy) NSString *content;@end#pararmmarkVPKCRequestManager.h#import#import "VPKCResponse.h"

@interface VPKCRequestManager : NSObject

/// 獲取當(dāng)前網(wǎng)絡(luò)是否可用

@property (assign, nonatomic, readonly) BOOL reachable;

/// 單利

+ (VPKCRequestManager *)sharedRequest;

/// 取消當(dāng)前請(qǐng)求任務(wù)

- (void)cancelCurrentTask;

/// 取消所有請(qǐng)求任務(wù)

- (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 "VPKCUtils.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;

/// 網(wǎng)絡(luò)是否可用

@property (assign, nonatomic, readwrite) BOOL reachable;

//

/// 當(dāng)前任務(wù)ID

@property (assign, nonatomic) NSInteger taskIdentifier;

//

//

//

/// 請(qǐng)求地址(前半段)

@property (strong, nonatomic) NSString *requestBaseUrl;

// 請(qǐng)求地址(后半段)

@property (copy, nonatomic) NSString *requestApiUrl;

/// 請(qǐng)求參數(shù)

@property (strong, nonatomic) NSDictionary *requestParame;

/// 請(qǐng)求方式

@property (assign, nonatomic) VPKCRequestMethod requestMethod;

@end

@implementation VPKCRequestManager

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

/// 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];

}

/// 取消當(dāng)前請(qǐng)求任務(wù)

- (void)cancelCurrentTask {

// cancel specific task

for (NSURLSessionDataTask* task in [_sessionManager tasks]) {

if (task.taskIdentifier == _taskIdentifier) {

[task cancel];

}

}

}

/// 取消所有請(qǐng)求任務(wù)

- (void)cancelAllTask {

[_sessionDataTask cancel];

}

+ (VPKCRequestManager *)sharedRequest {

static VPKCRequestManager *requestManage;

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

requestManage = [[self alloc] initPrivate];

});

return requestManage;

}

- (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;

}

//// 設(shè)置請(qǐng)求頭

- (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:@"連接服務(wù)器異常" 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:@"網(wǎng)絡(luò)連接失敗" 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;

}

@end

在VPKCUtils文件中 ——————/** 輔助工具類阵具,根據(jù)需求進(jìn)行添加 */

/**

*? 將字符串轉(zhuǎn)化為字典

*

*? @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;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末碍遍,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子阳液,更是在濱河造成了極大的恐慌怕敬,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,214評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件帘皿,死亡現(xiàn)場離奇詭異东跪,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)鹰溜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門虽填,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人曹动,你說我怎么就攤上這事斋日。” “怎么了墓陈?”我有些...
    開封第一講書人閱讀 152,543評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵恶守,是天一觀的道長第献。 經(jīng)常有香客問我,道長兔港,這世上最難降的妖魔是什么庸毫? 我笑而不...
    開封第一講書人閱讀 55,221評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮押框,結(jié)果婚禮上岔绸,老公的妹妹穿的比我還像新娘。我一直安慰自己橡伞,他們只是感情好盒揉,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,224評(píng)論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著兑徘,像睡著了一般刚盈。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上挂脑,一...
    開封第一講書人閱讀 49,007評(píng)論 1 284
  • 那天藕漱,我揣著相機(jī)與錄音,去河邊找鬼崭闲。 笑死肋联,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的刁俭。 我是一名探鬼主播橄仍,決...
    沈念sama閱讀 38,313評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼牍戚!你這毒婦竟也來了侮繁?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,956評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤如孝,失蹤者是張志新(化名)和其女友劉穎宪哩,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體第晰,經(jīng)...
    沈念sama閱讀 43,441評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡锁孟,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,925評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了茁瘦。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片罗岖。...
    茶點(diǎn)故事閱讀 38,018評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖腹躁,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情南蓬,我是刑警寧澤纺非,帶...
    沈念sama閱讀 33,685評(píng)論 4 322
  • 正文 年R本政府宣布哑了,位于F島的核電站,受9級(jí)特大地震影響烧颖,放射性物質(zhì)發(fā)生泄漏弱左。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,234評(píng)論 3 307
  • 文/蒙蒙 一炕淮、第九天 我趴在偏房一處隱蔽的房頂上張望拆火。 院中可真熱鬧,春花似錦涂圆、人聲如沸们镜。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽模狭。三九已至,卻和暖如春踩衩,著一層夾襖步出監(jiān)牢的瞬間嚼鹉,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評(píng)論 1 261
  • 我被黑心中介騙來泰國打工驱富, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留锚赤,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,467評(píng)論 2 352
  • 正文 我出身青樓褐鸥,卻偏偏與公主長得像线脚,于是被迫代替她去往敵國和親净捅。 傳聞我的和親對(duì)象是個(gè)殘疾皇子褥傍,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,762評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容