iOS网络资料首页投稿(暂停使用,暂停投稿)iOS Developer

网络请求--对AFN的封装

2016-07-04  本文已影响1386人  倚楼听风雨wing

网络框架封装##

查看AFN的源码会发现,AFN这套框架内部的GET,POST,DELETE,PUT,HEAD,PACH等方法都走了一个主方法,可是在AFN的头文件中却没有这个方法的声明,也就是说我们外部不能直接访问.

我的网络框架###

创建一个WYNetworkTool继承自AFHTTPSessionManager,然后在.h中编写如下代码

typedef enum : NSUInteger {
    WYNetworkMethodGET = 0, 
    WYNetworkMethodPOST
} WYNetWorkMethod;
/// 网络请求回调类型
///
/// @param result 返回结果
/// @param error  错误信息
typedef void (^WYRequestCallBack)(id result, NSError *error);

@interface WYNetWorkTool : AFHTTPSessionManager

+ (instancetype)sharedNetworkTool;

/// 网络请求,封装了GET和POST
///
/// @param method     枚举,GET/POST
/// @param URLString  baseURL之后的地址
/// @param parameters 请求参数
/// @param finished   返回回调
- (void)requestWithMethod:(WYNetWorkMethod)method URLString:(NSString *)URLString parameters:(id)parameters finished:(WYRequestCallBack)finished;

在.m中编写如下代码.解释:因为在AFN内部的主方法没有暴露在.h中所以我们无法直接访问,可以通过定义协议,然后遵守协议,再直接调用该内部方法.这里主要就是因为AFHTTPSessionManager实现了该方法,OC做为动态类型语言,在使用该方法的时候是能够动态的找到的.我们这里的协议想到于对方法做一个前置生命,使其编译器不会报错.

#import "WYNetWorkTool.h"

NSString *const Course_Base_URL = @"https://api.coursera.org/";

@protocol WYNetworkToolProxy <NSObject>

@optional
/// AFN 内部的数据访问方法
///
/// @param method           HTTP 方法
/// @param URLString        URLString
/// @param parameters       请求参数字典
/// @param uploadProgress   上传进度
/// @param downloadProgress 下载进度
/// @param success          成功回调
/// @param failure          失败回调
///
/// @return NSURLSessionDataTask,需要 resume
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;

@end

@interface WYNetWorkTool() <WYNetworkToolProxy>

@end

@implementation WYNetWorkTool

+ (instancetype)sharedNetworkTool {
    static WYNetWorkTool *instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] initWithBaseURL:[NSURL URLWithString:Course_Base_URL]];
    });
    
    return instance;
}

- (instancetype)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    
    if (self) {
        [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
        }];
        [self.reachabilityManager startMonitoring];
        //        self.requestSerializer = [AFgzipRequestSerializer serializer];
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
        [(AFJSONResponseSerializer *)self.responseSerializer setRemovesKeysWithNullValues:YES];
    }
    return self;
}

/// 网络请求,封装了GET和POST
///
/// @param method     枚举,GET/POST
/// @param URLString  baseURL之后的地址
/// @param parameters 请求参数
/// @param finished   返回回调
- (void)requestWithMethod:(WYNetWorkMethod)method URLString:(NSString *)URLString parameters:(id)parameters finished:(WYRequestCallBack)finished {
    URLString = URLString == nil ? @"" : URLString;
    NSString *methodName = (method == WYNetworkMethodGET) ? @"GET" : @"POST";
    NSString *urlStr = [NSString stringWithFormat:@"api/courses.v1/%@", URLString];
    
    [[self dataTaskWithHTTPMethod:methodName URLString:urlStr parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, id responseObject) {

        finished(responseObject, nil);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSLog(@"网络请求错误 %@", error.localizedDescription);
        
        finished(nil, error);
    }] resume];
}

@end

上一篇下一篇

猜你喜欢

热点阅读