如题利用单例模式对AFNetworking进行简单的封装(仅仅是封装了最基本的GET,POST请求)。供新手使用。
首先你得先装好
.h文件中AFNetworking框架......这个就不用多说了吧......
#import <AFNetworking/AFNetworking.h>
//成功时的回调
typedef void(^successBlock)(id responseObjects);
//失败时的回调
typedef void(^failureBlock)(NSError *error);
@interface HBQNetWorkTools : AFHTTPSessionManager
//单例模式
+ (instancetype)SharedManager;
//Get请求方式
- (void)get_RequestWithUrl:(NSString *)urlString
parameters:(NSDictionary *)parameters
successBlock:(successBlock)success
failureBlock:(failureBlock)failure;
//post请求方式
- (void)post_RequestWithUrl:(NSString *)urlString
parameters:(NSDictionary *)parameters
successBlock:(successBlock)success
failureBlock:(failureBlock)failure;
@end
.m文件中
#import "HBQNetWorkTools.h"
@implementation HBQNetWorkTools
#pragma mark - 单例模式
+ (instancetype)SharedManager {
static HBQNetWorkTools *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
instance = [[HBQNetWorkTools alloc] initWithSessionConfiguration:configuration];
//设置请求格式(默认格式为二进制格式)
instance.requestSerializer = [AFJSONRequestSerializer serializer];
//设置可接受的响应格式
instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
//设置请求超时时间(默认10s)
instance.requestSerializer.timeoutInterval = 10.0;
});
return instance;
}
#pragma mark - get网络请求
- (void)get_RequestWithUrl:(NSString *)urlString parameters:(NSDictionary *)parameters successBlock:(successBlock)success failureBlock:(failureBlock)failure {
[[HBQNetWorkTools SharedManager] GET:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
#pragma mark - post网络请求
- (void)post_RequestWithUrl:(NSString *)urlString parameters:(NSDictionary *)parameters successBlock:(successBlock)success failureBlock:(failureBlock)failure {
[[HBQNetWorkTools SharedManager]POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure (error);
}];
}
@end
网友评论