ios网络请求:AFNetWorking最实用封装

最简洁 最实用 一目了然的AFNetWorking封装

相信大家访问服务器都在用AFNetWorking,因为每次请求都要设置属性外加传递参数,弄的整个类看起来十分繁杂亢余。所以决定将请求过程封装。使调用的类仅处理服务器返回的数据。
该文章仅封装了get和post请求,仅传递了必要的参数,大家可以根据自己的需求添加需要的属性方法。重要的是使用后代码十分简洁明朗。(后面会附使用效果图。)
就一个request类

request类

属性:url,参数,类型
方法:执行请求
数据处理,通过delegate实现
头文件:

#import 

//请求类型
typedef enum Tim_RequestType {
    kTim_Request_Get,
    kTim_Request_Post,
    kTim_Request_Other
}Tim_RequestType;

//通过代理来处理服务器返回的数据
@protocol Tim_RequestDelegate 

@required
- (void)requestFinishedSuccessed:(NSDictionary *)dictionary;
- (void)requestFinishedFailed:(NSDictionary *)dictionary;
@optional
- (void)requestFailed:(NSError *)error;
@end

@interface Tim_Request : NSObject

//请求地址
@property (nonatomic,copy) NSString *requestUrl;
//请求参数
@property (strong,nonatomic) NSMutableDictionary *requestParams;
//请求类型
@property (assign,nonatomic) Tim_RequestType requestType;

@property (nonatomic, weak) id delegate;

//初始化
-(id) initWithDelegate:(id)delegate;
//执行请求
-(void) requestServer;

@end

实现:
首先初始化request对象,并且指定delegate

-(id) initWithDelegate:(id)delegate{
    self = [super init];
    if(self){
        _requestUrl = [[NSString alloc] init];
        _requestType = kTim_Request_Get;
        _requestParams = [[NSMutableDictionary alloc] init];
        _delegate = delegate;
    }
    return self;
}

然后就执行请求,通过请求类型来决定具体执行方法,如果需要不同类型的请求或操作,我们只需要添加请求类型以及该请求的执行方法就ok

-(void) requestServer{
    switch (self.requestType) {
        case kTim_Request_Get:
            [self executeGetRequest];
            break;
        case kTim_Request_Post:
            [self executePostRequest];
            break;
        case kTim_Request_Other:
            [self executeOtherRequest];
            break;
        default:
            break;
    }
}

执行具体请求,得到服务器返回的数据
get请求

-(void) executeGetRequest{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"text/plain", nil];
    
    [manager GET:self.requestUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里可以获取到目前的数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"TIM_GET请求成功:%@", responseObject);
        [self callBackFinishedWithDictionary:responseObject];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"TIM_GET请求失败%@", [error localizedDescription]);
        [self callBackFaild:error];
    }];
}

post请求

-(void) executePostRequest{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    if ([self.requestParams allKeys].count == 0) {
        self.requestParams = nil;
    }
    
    [manager POST:self.requestUrl parameters:self.requestParams progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"TIM_POST请求成功:%@", responseObject);
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"TIM_POST请求成功dictionary:%@", dictionary);
        [self callBackFinishedWithDictionary:dictionary];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"TIM_POST请求失败:%@", error.description);
        [self callBackFaild:error];
    }];
}

得到服务器数据之后,便通过delegate具体去处理数据
这里一定要根据自己服务器返回的数据来判断,此处是我自己访问服务器完成后必定会返回code == xx,成功1,失败其它

-(void) callBackFinishedWithDictionary:(NSDictionary *)dictionary{
    
    if (dictionary) {
        //删除空的value
        dictionary = [[self deleteAllNullValueInDictionary:dictionary] copy];
        //这里一定要根据自己服务器返回的数据来判断
        NSString *string = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"code"]];
        if([string isEqualToString:@"1"]){
            if(_delegate && [_delegate respondsToSelector:@selector(requestFinishedSuccessed:)]){
                [_delegate requestFinishedSuccessed:dictionary];
            }
        }else{
            if (_delegate && [_delegate respondsToSelector:@selector(requestFinishedFailed:)]) {
                [_delegate requestFinishedFailed:dictionary];
            }
        }
    }
}

-(void) callBackFaild:(NSError *)error{
    if (_delegate && [_delegate respondsToSelector:@selector(requestFailed:)]) {
        [_delegate requestFailed:error];
    }
}

使用:

包含头文件,添加Tim_RequestDelegate

#import "YourSelf_ViewController.h"
#import "Tim_Request.h"

@interface YourSelf_ViewController ()
{
    Tim_Request * aRequest;
    Tim_Request * bRequest;
    Tim_Request * cRequest;
}

初始化的时候指定delegate

aRequest = [[Tim_Request alloc] initWithDelegate:self];
bRequest = [[Tim_Request alloc] initWithDelegate:self];
cRequest = [[Tim_Request alloc] initWithDelegate:self];
// 如下也是没问题的
aRequest = [[Tim_Request alloc] init];
aRequest.delegate = self;
...

然后我们就配置请求参数,多少请求都不怕
在需要请求服务器的地方直接调用[self accessServer:xRequest]

#pragma mark ------------配置access server params

-(void) accessServer:(Tim_Request *)request {
    if(request == aRequest){
        request.requestType = kTim_Request_Get;
        request.requestUrl = @"http://....";
    }
    if (request == bRequest) {
        request.requestType = kTim_Request_Post;
        request.requestUrl = @"http://....";
        request.requestParams[@"key1"] = @"...";
        request.requestParams[@"key2"] = @"...";
    }
    if (request == cRequest) {
        //...同上自己设置
    }
    [request requestServer];
}

然后就是delegate的实现了,非常之简洁明了,根据自己需求来做

#pragma mark ------------Tim_RequestDelegate
- (void)requestFinishedSuccessed:(NSDictionary *)dictionary {
    //接收数据后do something...
    if(request == aRequest){
        //接收字典的数据do something...
        NSString *xxx = [dictionary objectForKey:@"xxx"];
        NSArray *xxx = [dictionary objectForKey:@"xxx"];
        NSDictionary *xxx = [dictionary objectForKey:@"xxx"];
    }
    if (request == bRequest) {
        //接收字典的数据do something...
    }
    if (request == cRequest) {
        //接收字典的数据do something...
    }
}
- (void)requestFinishedFailed:(NSDictionary *)dictionary {
      //同上...
}
- (void)requestFailed:(NSError *)error {
}

参考:基于AFNetworking封装网络请求

你可能感兴趣的:(ios网络请求:AFNetWorking最实用封装)