#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
/// 网络请求枚举
typedef enum : NSUInteger {
GET,
POST,
} WZRequestMethod;
@interface NetworkTools : AFHTTPSessionManager
+ (instancetype)sharedTools;
- (void)request:(WZRequestMethod)method URLString:(NSString *)URLString parameters:(id)parameters finished:(void (^)(id result, NSError *error))finished;
@end
==========================================
#import "NetworkTools.h"
/// 网络工具协议
@protocol NetworkToolsProxy <NSObject>
/// 网络请求方法
///
/// @param method HTTP 请求方法
/// @param URLString URLString
/// @param parameters 参数字典
/// @param success 成功回调
/// @param failure 失败回调
///
/// @return NSURLSessionDataTask
@optional
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *, id))success
failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;
@end
/// 遵守网络协议 - 为了能够欺骗 Xcode 给一个智能提示,以及编译通过!
@interface NetworkTools() <NetworkToolsProxy>
@end
@implementation NetworkTools
+ (instancetype)sharedTools {
static NetworkTools *tools;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 注意:末尾需要包含 '/'
NSURL *baseURL = [NSURL URLWithString:@"http://httpbin.org/"];
tools = [[self alloc] initWithBaseURL:baseURL];
// 设置反序列化格式
tools.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
});
return tools;
}
- (void)request:(WZRequestMethod)method URLString:(NSString *)URLString parameters:(id)parameters finished:(void (^)(id, NSError *))finished {
NSString *methodName = (method == GET) ? @"GET" : @"POST";
// dataTaskWithHTTPMethod本类没有实现方法,但是父类实现了
// 在调用方法的时候,如果本类没有提供,直接调用父类的方法,AFN 内部已经实现!
[[self dataTaskWithHTTPMethod:methodName URLString:URLString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
finished(responseObject, nil);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"%@", error);
finished(nil, error);
}] resume];
================================================
- (void)demo {
[[NetworkTools sharedTools] request:GET URLString:@"http://httpbin.org/get" parameters:@{@"name": @"zhangsan", @"age": @18} finished:^(id result, NSError *error) {
if (error != nil) {
NSLog(@"出错了");
return;
}
NSLog(@"%@", result);
}];
}