从苹果系统自带的请求类,到ASIHttpRequest第三方请求类,再到AFNetWorking第三方请求类,目前只要牵扯到数据请求,基本上都是用AFN,所以,这里纯粹是记录下:
hRequestTools.h
#import <Foundation/Foundation.h> /**
* 网络请求类型
*/
typedef NS_ENUM(NSUInteger,HttpRequestType) {
/**
* get请求
*/
HttpRequestTypeGet = ,
/**
* post请求
*/
HttpRequestTypePost =
}; @interface hRequestTools : NSObject /**
* 发送网络请求
*
* @param URLString 请求的网址字符串
* @param parameters 请求的参数
* @param type 请求的类型
* @param success 请求的结果
*/
+ (void)requestWithURLString:(NSString *)URLString
parameters:(id)parameters
type:(HttpRequestType)type
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
hRequestTools.m
#pragma mark 封装的请求方法
+ (void)requestWithURLString:(NSString *)URLString
parameters:(id)parameters
type:(HttpRequestType)type
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer.timeoutInterval = 30.0f;
switch (type) {
case HttpRequestTypeGet:
{
[manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
id jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
success(jsons);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}]; }
break;
case HttpRequestTypePost:
{
[manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
id jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
success(jsons);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
break;
default:
break;
} }
请求里面如果要加缓存的话,可以和YYCache这个第三方配合使用,
关于YYCache,可以推荐几个链接:http://www.jianshu.com/p/b8dcf6634fab