写在前面
分享此实例,希望能帮到一些像我一样的初学者。
代码有哪些不好的地方,还望各位读者多多指教。
源码请戳这
头文件 JDNetworkRequest.h
#import <Foundation/Foundation.h>
@protocol JDNetworkRequestDatasource <NSObject>
- (NSString *)jdNetworkRequestBaseURLString; //用于初始化的网址
@end
//网络请求类型
typedef NS_ENUM(NSUInteger,JDNetworkRequestType) {
JDNetworkRequestTypePost,
JDNetworkRequestTypeGet,
JDNetworkRequestTypeHead,
JDNetworkRequestTypePut,
JDNetworkRequestTypeDelete
};
typedef void(^JDNetworkRequestResultBlock)(id responseObject,NSError *error);
@interface JDNetworkRequest : NSObject
@property (nonatomic, weak) id<JDNetworkRequestDatasource> datasource;
/**
* 发送网络请求
*
* @param urlString 网址字符串
* @param parameters 参数
* @param type 请求类型
* @param resultBlock 返回结果:responseObject,error
*/
- (void)jd_requestWithURLString:(NSString *)urlString
parameters:(NSDictionary *)parameters
type:(JDNetworkRequestType)type
resultBlock:(JDNetworkRequestResultBlock)resultBlock;
@end
实现文件 JDNetworkRequest.m
类扩展部分
@interface JDNetworkRequest ()
@property (nonatomic, strong) AFHTTPSessionManager *manager;
@property (nonatomic, assign, getter=isConnected) BOOL connected; /**<网络是否连接*/
@end
介绍网络请求方法之前,先介绍几个会用到的方法
- 判断网络是否连接的方法
- (BOOL)isConnected {
struct sockaddr zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sa_len = sizeof(zeroAddress);
zeroAddress.sa_family = AF_INET;
SCNetworkReachabilityRef defaultRouteReachability =
SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags =
SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags) {
printf("Error. Count not recover network reachability flags\n");
return NO;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
return (isReachable && !needsConnection) ? YES : NO;
}
-
self.manager懒加载
- (AFHTTPSessionManager *)manager { if (!_manager) { NSString *baseUrlString = [self.datasource jdNetworkRequestBaseURLString]; _manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:baseUrlString]]; } return _manager; }
统一处理返回参数的方法
- (void)handleRequestResultWithDataTask:(NSURLSessionDataTask *)task
responseObject:(id)responseObject
error:(NSError *)error
resultBlock:(JDNetworkRequestResultBlock)resultBlock {
//do something here...
JD_EXECUTE_BLOCK(resultBlock,responseObject,error);
}
网络请求方法的具体实现如下:
@implementation JDNetworkRequest
- (void)jd_requestWithURLString:(NSString *)urlString
parameters:(NSDictionary *)parameters
type:(JDNetworkRequestType)type
resultBlock:(JDNetworkRequestResultBlock)resultBlock {
if (!self.isConnected) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示"
message:@"没有网络,建议在手机设置中打开网络"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"退出", nil];
[alertView show];
return;
}
if (![self.datasource respondsToSelector:@selector(jdNetworkRequestBaseURLString)]) { //未实现datasource
JDLog(@"error:未实现JDNetworkRequestDatasource");
return;
}
NSSet *acceptableContentTypes = [NSSet setWithObjects:@"application/json",
@"text/html",
@"text/json",
@"text/javascript",
@"text/plain", nil];
self.manager.operationQueue.maxConcurrentOperationCount = 5;
self.manager.requestSerializer.timeoutInterval = 3;
self.manager.responseSerializer.acceptableContentTypes = acceptableContentTypes;
switch (type) {
case JDNetworkRequestTypePost: {
[self.manager POST:urlString
parameters:parameters
success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
[self handleRequestResultWithDataTask:task
responseObject:responseObject
error:nil
resultBlock:resultBlock];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[self handleRequestResultWithDataTask:task
responseObject:nil
error:error
resultBlock:resultBlock];
}];
break;
}
...
其他JDNetworkRequestType限于篇幅,就不一一列出,
有兴趣的可以看源码
如何使用?
-
实现JDNetworkRequestDatasource
#pragma mark - JDNetworkRequestDatasource- (NSString *)jdNetworkRequestBaseURLString { //TODO: 网址是无效的,请自行更换 return @"http://www.example.com"; }
调用网络请求方法
JDNetworkRequest *networkRequest = [[JDNetworkRequest alloc]init];
networkRequest.datasource = self;
//TODO: 以下网址及参数是无效的,请自行更换
NSString *urlString = @"http://www.example.com/?_c=thread&_a=threadInfo";
NSDictionary *parameters = @{ @"msg_id" : @0,
@"sign" : @"149f7fd34ba2a961ab52ac0225da7f6c",
@"time" : @"1447414060",
@"token" : @"FMXa++Q0Lwkue+Mdirr6lw==",
@"thread_id" : @"198"
};
[networkRequest jd_requestWithURLString:urlString
parameters:parameters
type:JDNetworkRequestTypePost
resultBlock:^(id responseObject, NSError *error) {
NSLog(@"%@",responseObject);
}];
写在最后
欢迎各位读者指教不足之处。