iOS 封装网络请求工具类(基于AFNetworking)
2017-05-14 本文已影响96人
ziyouzhe4
二.网络请求工具类(OC)
1.导入框架和创建类
1).先导入第三方库AFNetworking
2).建立NetworkTool
类继承于AFHTTPSessionManager
,继承于AFHTTPSessionManager
的原因是发送请求需要调用到manager,而直接继承于AFHTTPSessionManager
可以直接调用内部的方法
2.添加网络请求方法和实现
1).方法声明
首先确定要传入的参数,有网址、请求参数、GET/POST方法,当网络请求成功后,会有responseObject
回调,所以还需要传入一个block
/** 创建网络请求工具类的单例 */
+ (instancetype)sharedTool;
/** 创建请求方法 */
- (void)requestWithURLString: (NSString *)URLString parameters: (NSDictionary *)parameters method: (NSString *)method callBack: (void(^)(id responseObject))callBack;
2).方法实现
单例
+ (instancetype)sharedTool {
static id instance; static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ instance = [[self alloc] initWithBaseURL:nil];
});
return instance;
}
//网络请求方法
- (void)requestWithURLString: (NSString *)URLString
parameters: (NSDictionary *)parameters
method: (NSString *)method
callBack: (void (^)(id))callBack {
//判断请求方法是GET还是POST
if ([method isEqualToString:@"GET"]) {
//调用AFN框架的方法
[self GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//如果请求成功,则回调responseObject
callBack(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//如果请求失败,控制台打印错误信息
NSLog(@"%@",error);
}];
}
if ([method isEqualToString:@"POST"]) {
[self POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
callBack(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}
}
三.网络请求工具类(Swift)
1.新建SwiftNetworkTool.swift
文件,SwiftNetworkTool类
继承于AFHTTPSessionManager
网络请求工具类(Swift).png
2.Swift版简洁好用,直接上代码
//单例
static let shared = SwiftNetworkTool()
//网络中间层的接口方法
func request(urlString: String, parameters: [String: Any]? = nil, method: String, callBack: @escaping (_ responseObject: Any?) -> ()) {
//网络请求成功的闭包
let succes = {
(task: URLSessionDataTask, response: Any?) in
callBack(response)
}
//网络请求失败的闭包
let failure = {
(task: URLSessionDataTask?, error: Error) in
print("\(error)")
callBack(nil)
}
if method == "GET" {
self.get(urlString, parameters: parameters, progress: nil, success: succes, failure: failure)
}
if method == "POST" {
self.post(urlString, parameters: parameters, progress: nil, success: succes, failure: failure)
}
}