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