Github link: github.com/Charlesyaox…
AFNetWorking->CYRequestManager->CYBaseRequest
Encapsulates the network request, involving three classes
1. AFNetworking
2. CYRequestManager
3. CYBaseRequestCopy the code
Design ideas
- Start by encapsulating AFNetworking, or CYRequestManager
- But CYRequestManager requires parameters and links, and parameters and links are still too exposed, so design the CYBaseRequest class
- When used, inherit CYBaseRequest, take the attributes of the class as parameters (model to JSON), convert the attributes into dictionary parameters, and send a request
- Simple packaging, gradually improve later
Case 1
Use CYBaseRequest directly
1. Create a request
CYBaseRequest *request = [CYBaseRequest new];
request.url = @"www.baidu.com";
// 2. Send request
[request sendRequestWithCompletionHandle:^(BOOL success, id response, NSString *message) {
}];
}Copy the code
Use case 2
Create a CYUserInfoRequest inherited from CYBaseRequest
CYUserInfoRequest.h
@interface CYUserInfoRequest : CYBaseRequest
@property (nonatomic.assign) NSInteger userId;
@end
CYUserInfoRequest.m
@implementation CYUserInfoRequest
- (instancetype)init {
self = [super init];
if (self) {
self.url = @" Request the required link";
}
return self;
}
@endHow to use it?@interface ViewController(a)
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
1. Create a request
CYUserInfoRequest *userInfoR = [CYUserInfoRequest new];
userInfoR.userId = 1;
// It can be set in.m
// userInfoR.url = @"www.baidu.com";
/ / is optional
// userInfoR.extraParams = @{
// @"username" : @"xxx"
/ /};
// 2. Set the request mode
userInfoR.methodType = CYRequestMethodTypePOST;
// 3. Send request
[userInfoR sendRequestWithCompletionHandle:^(BOOL success, id response, NSString *message) {
}];
}
@end
}Copy the code
Design code example – CYRequestManager
#import "AFNetworking.h"
#import "CYRequestConstant.h"
// Requested a successful callback
typedef void(^CYRequestManagerSuccessHandle)(NSURLSessionTask *task, id response);
// Request failed callback
typedef void(^CYRequestManagerFailureHandle)(NSURLSessionTask *task, NSError *error);
@interface CYRequestManager : NSObject
/** Request By NSURLSession @param URLString @param Params Request parameter @param methodType Request method @param serializerType Data parsing type @param successHandle Callback when a request succeeds @param failureHandle Callback when a request fails */
+ (void)requestWithURLString:(NSString *)URLString
params:(NSDictionary *)params
methodType:(CYRequestMethodType)methodType
serializerType:(CYResponseSeializerType)serializerType
successHandle:(CYRequestManagerSuccessHandle)successHandle
failureHandle:(CYRequestManagerFailureHandle)failureHandle;
/** a multipart 'POST' request By NSURLSession @param URLString @param params request parameter @param serializerType Data parsing type @param constructingBody Adds a request body @param successHandle A callback for a successful request @param failureHandle A callback for a failed request */
+ (void)POSTWithURLString:(NSString *)URLString
params:(NSDictionary *)params
serializerType:(CYResponseSeializerType)serializerType
constructingBody:(void(^) (id<AFMultipartFormData> formData))constructingBody
successHandle:(CYRequestManagerSuccessHandle)successHandle
failureHandle:(CYRequestManagerFailureHandle)failureHandle;
@end
#import "CYRequestManager.h"
#import "AFNetworking.h"
@interface AFHTTPSessionManager (Shared)
+ (instancetype)sharedManager;
@end
@implementation AFHTTPSessionManager (Shared)
+ (instancetype)sharedManager {
static AFHTTPSessionManager *_singleton;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_singleton = [AFHTTPSessionManager manager];
_singleton.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json".@"text/plain".@"text/json".@"text/javascript".@"text/html".nil];
});
return _singleton;
}
@end
@implementation CYRequestManager
+ (void)requestWithURLString:(NSString *)URLString
params:(NSDictionary *)params
methodType:(CYRequestMethodType)methodType
serializerType:(CYResponseSeializerType)serializerType
successHandle:(CYRequestManagerSuccessHandle)successHandle
failureHandle:(CYRequestManagerFailureHandle)failureHandle {
AFHTTPSessionManager *manager = [AFHTTPSessionManager sharedManager];
manager.responseSerializer = [self responseSearalizerWithSerilizerType:serializerType];
switch (methodType) {
case CYRequestMethodTypeGET: [manager GET:URLString parameters:params progress:nil success:successHandle failure:failureHandle]; break;
case CYRequestMethodTypePOST: [manager POST:URLString parameters:params progress:nil success:successHandle failure:failureHandle]; break;
case CYRequestMethodTypePUT: [manager PUT:URLString parameters:params success:successHandle failure:failureHandle]; break;
case CYRequestMethodTypePATCH: [manager PATCH:URLString parameters:params success:successHandle failure:failureHandle]; break;
case CYRequestMethodTypeDELETE: [manager DELETE:URLString parameters:params success:successHandle failure:failureHandle]; break;
case CYRequestMethodTypeHEAD: [manager HEAD:URLString parameters:params success:^(NSURLSessionDataTask* _Nonnull task) { ! successHandle ? : successHandle(task,nil);
} failure:failureHandle]; break; }} + (void)POSTWithURLString:(NSString *)URLString
params:(NSDictionary *)params
serializerType:(CYResponseSeializerType)serializerType
constructingBody:(void(^) (id<AFMultipartFormData> formData))constructingBody
successHandle:(CYRequestManagerSuccessHandle)successHandle
failureHandle:(CYRequestManagerFailureHandle)failureHandle {
AFHTTPSessionManager *manager = [AFHTTPSessionManager sharedManager];
manager.responseSerializer = [self responseSearalizerWithSerilizerType:serializerType];
[manager POST:URLString parameters:params constructingBodyWithBlock:constructingBody progress:nil success:successHandle failure:failureHandle];
}
+ (AFHTTPResponseSerializer *)responseSearalizerWithSerilizerType:(CYResponseSeializerType)serilizerType {
switch (serilizerType) {
case CYResponseSeializerTypeDefault: return [AFJSONResponseSerializer serializer]; break;
case CYResponseSeializerTypeJSON: return [AFJSONResponseSerializer serializer]; break;
case CYResponseSeializerTypeXML: return [AFXMLParserResponseSerializer serializer]; break;
case CYResponseSeializerTypePlist: return [AFPropertyListResponseSerializer serializer]; break;
case CYResponseSeializerTypeCompound: return [AFCompoundResponseSerializer serializer]; break;
case CYResponseSeializerTypeImage: return [AFImageResponseSerializer serializer]; break;
case CYResponseSeializerTypeData: return [AFHTTPResponseSerializer serializer]; break;
default: return [AFJSONResponseSerializer serializer]; break; }}@endCopy the code
Design code example – CYBaseRequest
#import "CYRequestConstant.h"
typedef void(^CYBaseRequestCompletionHandle)(BOOL success, id response, NSString *message);
@interface CYBaseRequest : NSObject
@property (nonatomic.copy) NSString *url;
@property (nonatomic.assign) CYRequestMethodType methodType;
@property (nonatomic.strong) NSDictionary *extraParams;
- (void)sendRequestWithCompletionHandle:(CYBaseRequestCompletionHandle)completionHandle;
@end
#import "CYBaseRequest.h"
#import "YYModel.h"
#import "CYRequestManager.h"
@implementation CYBaseRequest
- (void)sendRequestWithCompletionHandle:(CYBaseRequestCompletionHandle)completionHandle {
if(! _url || ! _url.length)return;
[CYRequestManager requestWithURLString:_url
params:[self params]
methodType:self.methodType
serializerType:CYResponseSeializerTypeJSON
successHandle:^(NSURLSessionTask *task, idresponse) { ! completionHandle ? : completionHandle(YES, response, nil);
} failureHandle:^(NSURLSessionTask *task, NSError*error) { ! completionHandle ? : completionHandle(NO.nil, error.description);
}];
}
- (NSDictionary *)params {
NSDictionary *json = self.yy_modelToJSONObject;
if ([json isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *params = [(NSDictionary *)json mutableCopy];
[params addEntriesFromDictionary:self.extraParams];
for (NSString *delKey in@ [@"url".@"methodType".@"extraParams"]) {
if([params.allKeys containsObject:delKey]) { [params removeObjectForKey:delKey]; }}for (id key in params.allKeys) {
id obj = [params objectForKey:key];
if(! obj || [obj isKindOfClass:[NSNull class]] || obj == (id)kCFNull) { [params removeObjectForKey:key]; }}return params;
}
return self.extraParams;
}
@endCopy the code