IOS开发之—— 在AFN基础上进行的网络请求的封装

网络请求的思路:如果请求成功的话AFN的responseObject就是解析好的。

1发送网络请求;get/post/或者别的 带上URL,需要传的参数

2判断后台网络状态码有没有请求成功;

3 请求成功:解析数据,刷新页面

4请求失败做处理

VPKCResponse.h

VPKCResponse.m

VPKCRequestManager.h

VPKCRequestManager.m

定义两个文件继承NSObject。

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

#pararmmark

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

/// 网络是否可用
@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

#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];
}

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

/// 取消所有请求任务
- (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;
}
//// 设置请求头
- (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;
}
@end

在VPKCUtils文件中 ——————/** 辅助工具类,根据需求进行添加 */

/**
 *  将字符串转化为字典
 *
 *  @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;
}

时间: 2024-10-12 20:22:46

IOS开发之—— 在AFN基础上进行的网络请求的封装的相关文章

iOS开发UI篇—Button基础

iOS开发UI篇—Button基础 一.简单说明 一般情况下,点击某个控件后,会做出相应反应的都是按钮 按钮的功能比较多,既能显示文字,又能显示图片,还能随时调整内部图片和文字的位置 二.按钮的三种状态 normal(普通状态) 默认情况(Default) 对应的枚举常量:UIControlStateNormal highlighted(高亮状态) 按钮被按下去的时候(手指还未松开) 对应的枚举常量:UIControlStateHighlighted disabled(失效状态,不可用状态) 如

IOS开发系列&mdash;Objective-C之基础概览

概览 前面我们已经用了几章内容进行C语言介绍,当然要通过几篇文章完整的介绍C语言的知识是不太现实的,例如C语言的文件操作.内存申请等我们都没有重点介绍,当然核心知识点基本都已经提到了,后面有时间我们会继续扩充.今天我们正式开始学习Objective-C,以后简称"ObjC",ObjC是在C语言的基础上加上了一层面向对象的特性,它完全兼容C语言,甚至可以混写C++.它是Mac OS X和IOS的主要开发语言,从IOS发布之后可以说ObjC的地位呈直线上升趋势,当前ObjC已经是仅次于C语

Delphi for iOS开发指南(1):在Mac上配置你的开发环境

http://cache.baiducontent.com/c?m=9d78d513d99516f11ab7cf690d678c3b584380122ba7a0020fd18438e4732b40506793ac57240773a4d20c1116dc4348adb0687d6d4566f58cc9fb57c0ebcc757a9f2743215dd01d05d36ef39c00388477cb4deedb5ca0bcfb3092aad2d2de49008a155e2bdea7960c575299

iOS开发项目篇—32添加上拉刷新数据

iOS开发项目篇—32添加上拉刷新数据 一.简单说明 图片示意 思路:可以自定义一个view(示意xib),在view中添加一个label和菊花,指示状态.把这个view设置为tableView的底部视图. 二.实现过程 1.新建一个类和xib,关联 (1)创建一个类,让其继承自UIView (2)创建一个xib文件,用来定义上拉提示框 (3)定义的xib文件,把类和xib文件进行关联 2.实现代码: YYlaodStatusesFooter.h文件 1 // 2 // YYlaodStatus

【iOS】网络请求框架封装

在使用网络请求的过程中,可以使用系统的框架.ASI.AF.MK等等,但是如果需要更换项目的网络请求框架(比如,项目之前用的ASI的框架,现在需要更换为AF),那么这将是一个浩大的工程.项目初期,怎么搭建网络请求框架,才可以让修改网络请求的工程量减到最小呢,这是我们今天要说的问题. 环境信息: Mac OS X 10.10.1 Xcode 6.1.1 iOS 8.1 正文 封装的网络请求框架一共三层: 第三层:ASI.AF或者其他网络请求方式.第二层:第二层分有基类与类目(Category)构成,

李洪强iOS开发之【零基础学习iOS开发】【01-前言】01-开篇

从今天开始,我就开始更新[零基础学习iOS开发]这个专题.不管你是否涉足过IT领域,也不管你是理科生还是文科生,只要你对iOS开发感兴趣,都可以来阅读此专题.我尽量以通俗易懂的语言,让每个人都能够看懂.若遇到不明白的地方或者对此文有异议,望及时评论. 一.什么是iOS 要想学习iOS开发,首先要搞清楚什么是iOS.iOS其实是一款操作系统,就像平时我们在电脑上用的XP.Win7,都是操作系统. 那什么是操作系统呢?操作系统其实是一种软件,是直接运行在硬件(电脑.手机等)上的最基本的系统软件,任何

iOS开发系列—Objective-C之基础概览oc格式化输出例子

概览 前面我们已经用了几章内容进行C语言介绍,当然要通过几篇文章完整的介绍C语言的知识是不太现实的,例如C语言的文件操作.内存申请等我们都没有重点介绍,当然核心知识点基本都已经提到了,后面有时间我们会继续扩充.今天我们正式开始学习Objective-C,以后简称"ObjC",ObjC是在C语言的基础上加上了一层面向对象的特性,它完全兼容C语言,甚至可以混写C++.它是Mac OS X和IOS的主要开发语言,从IOS发布之后可以说ObjC的地位呈直线上升趋势,当前ObjC已经是仅次于C语

李洪强iOS开发之【零基础学习iOS开发】【02-C语言】02-第一个C语言程序

前言 前面已经唠叨了这么多理论知识,从这讲开始,就要通过接触代码来学习C语言的语法.学习任何一门语言,首先要掌握的肯定是语法.学习C语言语法的目的:就是能够利用C语言编写程序,然后运行程序跟硬件(计算机.手机等硬件设备)进行交互.由于我们的最终目的是学习iOS开发,学习iOS开发的话必须在Mac系统下,因此我就在Mac系统环境下开发C语言程序,而不是在Windows环境下. 接下来,就在Mac系统环境下编写第一个C语言程序,最后把程序运行起来,跟计算机做一个小小的互动 一.编写第一个C语言程序-

李洪强iOS开发之【零基础学习iOS开发】【01-前言】02-准备

在上一讲中,介绍了什么是iOS开发.说简单一点,iOS开发,就是开发运行在iPhone或者iPad上的软件.这么一说完,应该有很多人就会产生一些疑惑,比如学习iOS开发是不是一定要买iPhone?需不需要买苹果电脑呢?学软件开发是不是一定要计算机专业的?因此,在这讲中,我会为广大有意学习iOS开发的朋友们进行解惑,说明一下学习iOS开发究竟需要那些准备. 一.程序设计语言 上一讲已经说到:要想开发一款软件,首先得学习一些相应的程序设计语言.至于iOS开发,需要学习的语言主要有:C.C++.Obj