首先说明下为什么要自己封装一层这个类,因为项目需要,不同的接口实现不同的通信协议,所以自己封装了一层来控制相关的类来处理一些操作!比如Get、Post、Put、Delete...
这个类也是主要封装了以上几个方法!
—————————————————————————————————————————————————————————————
我用了cocoaPods来管理AFNetworking。这个应该不用再说明怎么导入使用这个类库了吧!
这里面还用到了UICKeyChainStore这个存储信息的第三方类
PDToast 还用了我自己写的的一个动态库PDFramework里面的一个功能
http://www.jianshu.com/writer#/notebooks/5366058/notes/4998769
—————————————————————————————————————————————————————————————
下面来说重点:
HttpsRequest.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface HttpsRequest : NSObject
+(HttpsRequest *)getInstance;
- (void)GetData:(NSMutableDictionary *)params :(NSString *)url andBlock:(void(^)(id requsetStr))block;
- (void)PostData:(NSMutableDictionary *)params :(NSString *)url andBlock:(void(^)(id requsetStr))block;
- (void)PUTData:(NSMutableDictionary *)params :(NSString *)url andBlock:(void(^)(id requsetStr))block;
- (void)DeleteData:(NSMutableDictionary *)params :(NSString *)url andBlock:(void(^)(id requsetStr))block;
@property (nonatomic, retain) UIView *selfView;
@end
HttpsRequest.m
#import "HttpsRequest.h"
#import <AFNetworking.h>
#import <CommonCrypto/CommonDigest.h>
#import "General.h"//这个是写配置的文件(这个文件里面写了一些宏定义,如果你需要直接使用这两个类的话,拷贝代码报警告或者错误的话,自行修改错误的地方吧!)
@implementation HttpsRequest
static AFHTTPSessionManager *manager;
static HttpsRequest *httpsRequest;
NSString *MyUrl;
NSMutableDictionary *Mydic;
UIView *errorView;
+(instancetype)getInstance
{
if (httpsRequest ==nil) {
httpsRequest = [[HttpsRequest alloc]init];
}
if (manager ==nil) {
manager = [AFHTTPSessionManager manager];
}
return httpsRequest;
}
- (instancetype)init
{
self = [super init];
return self;
}
- (void)GetData:(NSMutableDictionary *)params :(NSString *)url andBlock:(void(^)(id requsetStr))block{
if (params == nil) {
params = [NSMutableDictionary new];
}
manager=[AFHTTPSessionManager manager];
manager.securityPolicy=[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
manager.requestSerializer=[AFJSONRequestSerializer serializer];
manager.responseSerializer=[AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
if (ISLOGIN) {
[manager.requestSerializer setValue:[UICKeyChainStore stringForKey:@"sessionID" service:keychainValue] forHTTPHeaderField:@"sid"];
}
[manager GET:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// NSLog(@"请求成功:%@", responseObject);
if (errorView) {
[errorView removeFromSuperview];
errorView = nil;
}
NSDictionary *JSON = [[NSDictionary alloc]initWithDictionary:responseObject];
NSLog(@"%@ 请求成功JSON:%@", url, JSON);
if ([[NSString stringWithFormat:@"%@",[JSON objectForKey:@"result"]]isEqualToString:@"1"]) {
if ([[NSString stringWithFormat:@"%@",[JSON objectForKey:@"data"]]isEqualToString:@"<null>"]) {
block(JSON);
return ;
}
if ([[JSON objectForKey:@"data"] isKindOfClass:[NSString class]] || [[JSON objectForKey:@"data"] isKindOfClass:[NSNumber class]]) {
block(JSON);
return ;
}
else
{
block([JSON objectForKey:@"data"]);
}
}
else
{
if ([[JSON objectForKey:@"error"] integerValue] ==1001) {
[self autoLoginInBySid:1 :@"" :params :url andBlock:^(id requestStr) {
block(requestStr);
}];
} else{
[self showErrorInfo:[[JSON objectForKey:@"error"] integerValue] :params :url];
block(@"0");
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[PDToast hiddenActivity];
NSLog(@"请求失败:%@", error.description);
NSString *str =@"error";
if ([[PDObject getInstance] isNetworkEnabled] == YES) {
}else
{
if (errorView) {
[errorView removeFromSuperview];
errorView = nil;
}
errorView = [[UIView alloc]initWithFrame:_selfView.bounds];
[self.selfView addSubview:errorView];
}
block(str);
}];
}
- (void)PostData:(NSMutableDictionary *)params :(NSString *)url andBlock:(void(^)(id requsetStr))block{
if (params == nil) {
params = [NSMutableDictionary new];
}
manager=[AFHTTPSessionManager manager];
manager.securityPolicy=[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
manager.requestSerializer=[AFJSONRequestSerializer serializer];
manager.responseSerializer=[AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
if (ISLOGIN) {
[manager.requestSerializer setValue:[UICKeyChainStore stringForKey:@"sessionID" service:keychainValue] forHTTPHeaderField:@"sid"];
}
else
{
[manager.requestSerializer setValue:nil forHTTPHeaderField:@"sid"];
}
[manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// NSLog(@"请求成功:%@", responseObject);
if (errorView) {
[errorView removeFromSuperview];
errorView = nil;
}
NSDictionary *JSON = [[NSDictionary alloc]initWithDictionary:responseObject];
NSLog(@"%@ 请求成功JSON:%@", url, JSON);
if ([[NSString stringWithFormat:@"%@",[JSON objectForKey:@"result"]]isEqualToString:@"1"]) {
if ([[NSString stringWithFormat:@"%@",[JSON objectForKey:@"data"]]isEqualToString:@"<null>"]) {
block(JSON);
return ;
}
if ([[JSON objectForKey:@"data"] isKindOfClass:[NSString class]] || [[JSON objectForKey:@"data"] isKindOfClass:[NSNumber class]]) {
block(JSON);
return ;
}
else
{
block([JSON objectForKey:@"data"]);
}
}
else
{
if ([[JSON objectForKey:@"error"] integerValue] ==1001) {
[self autoLoginInBySid:1 :@"" :params :url andBlock:^(id requestStr) {
block(requestStr);
}];
} else{
[self showErrorInfo:[[JSON objectForKey:@"error"] integerValue] :params :url];
block(@"0");
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[PDToast hiddenActivity];
NSLog(@"请求失败:%@", error.description);
NSString *str =@"error";
if ([[PDObject getInstance] isNetworkEnabled] == YES) {
}else
{
if (errorView) {
[errorView removeFromSuperview];
errorView = nil;
}
errorView = [[UIView alloc]initWithFrame:_selfView.bounds];
[self.selfView addSubview:errorView];
}
block(str);
}];
}
- (void)PUTData:(NSMutableDictionary *)params :(NSString *)url andBlock:(void(^)(id requsetStr))block{
manager=[AFHTTPSessionManager manager];
manager.securityPolicy=[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
manager.requestSerializer=[AFJSONRequestSerializer serializer];
manager.responseSerializer=[AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//[manager.requestSerializer setValue:@"text/html;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
if (ISLOGIN) {
[manager.requestSerializer setValue:[UICKeyChainStore stringForKey:@"sessionID" service:keychainValue] forHTTPHeaderField:@"sid"];
}
[manager PUT:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (errorView) {
[errorView removeFromSuperview];
errorView = nil;
}
NSDictionary *JSON = [[NSDictionary alloc]initWithDictionary:responseObject];
NSLog(@"%@ 请求成功JSON:%@", url, JSON);
if ([[NSString stringWithFormat:@"%@",[JSON objectForKey:@"result"]]isEqualToString:@"1"]) {
if ([[NSString stringWithFormat:@"%@",[JSON objectForKey:@"data"]]isEqualToString:@"<null>"]) {
block(JSON);
return ;
}
if ([[JSON objectForKey:@"data"] isKindOfClass:[NSString class]] || [[JSON objectForKey:@"data"] isKindOfClass:[NSNumber class]]) {
block(JSON);
return ;
}
else
{
block([JSON objectForKey:@"data"]);
}
}
else
{
if ([[JSON objectForKey:@"error"] integerValue] ==1001) {
[self autoLoginInBySid:1 :@"" :params :url andBlock:^(id requestStr) {
block(requestStr);
}];
} else{
[self showErrorInfo:[[JSON objectForKey:@"error"] integerValue] :params :url];
block(@"0");
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[PDToast hiddenActivity];
NSLog(@"请求失败:%@", error.description);
NSString *str =@"error";
if ([[PDObject getInstance] isNetworkEnabled] == YES) {
}else
{
if (errorView) {
[errorView removeFromSuperview];
errorView = nil;
}
errorView = [[UIView alloc]initWithFrame:_selfView.bounds];
[self.selfView addSubview:errorView];
}
block(str);
}];
}
- (void)DeleteData:(NSMutableDictionary *)params :(NSString *)url andBlock:(void(^)(id requsetStr))block{
manager=[AFHTTPSessionManager manager];
manager.securityPolicy=[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
manager.requestSerializer=[AFJSONRequestSerializer serializer];
manager.responseSerializer=[AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
// [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
if (ISLOGIN) {
[manager.requestSerializer setValue:[UICKeyChainStore stringForKey:@"sessionID" service:keychainValue] forHTTPHeaderField:@"sid"];
}
[manager DELETE:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (errorView) {
[errorView removeFromSuperview];
errorView = nil;
}
NSDictionary *JSON = [[NSDictionary alloc]initWithDictionary:responseObject];
NSLog(@"%@ 请求成功JSON:%@", url, JSON);
if ([[NSString stringWithFormat:@"%@",[JSON objectForKey:@"result"]]isEqualToString:@"1"]) {
if ([[NSString stringWithFormat:@"%@",[JSON objectForKey:@"data"]]isEqualToString:@"<null>"]) {
block(JSON);
return ;
}
if ([[JSON objectForKey:@"data"] isKindOfClass:[NSString class]] || [[JSON objectForKey:@"data"] isKindOfClass:[NSNumber class]]) {
block(JSON);
return ;
}
else
{
block([JSON objectForKey:@"data"]);
}
}
else
{
if ([[JSON objectForKey:@"error"] integerValue] ==1001) {
[self autoLoginInBySid:1 :@"" :params :url andBlock:^(id requestStr) {
block(requestStr);
}];
} else{
[self showErrorInfo:[[JSON objectForKey:@"error"] integerValue] :params :url];
block(@"0");
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[PDToast hiddenActivity];
NSLog(@"请求失败:%@", error.description);
NSString *str =@"error";
if ([[PDObject getInstance] isNetworkEnabled] == YES) {
}else
{
if (errorView) {
[errorView removeFromSuperview];
errorView = nil;
}
errorView = [[UIView alloc]initWithFrame:_selfView.bounds];
[self.selfView addSubview:errorView];
}
block(str);
}];
}
#pragma mark 类方法
- (NSString*)sha1:(NSString*)input
{
const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:input.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, (unsigned)(long)data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}
- (void)showErrorInfo:(NSInteger )errorCode :(NSDictionary *)parms :(NSString *)url
{
switch (errorCode) {
case 0:
NSLog(@"");
break;
case 1001:
// [PDToast showWithText: @"系统异常,请重新登录" bottomOffset:80];
break;
case 2001:
[PDToast showWithText: @"系统异常,请稍候重试" bottomOffset:80];
break;
case 4001:
[PDToast showWithText: @"验证码错误" bottomOffset:80];
break;
case 4002:
[PDToast showWithText: @"验证码过期" bottomOffset:80];
break;
case 4003:
[PDToast showWithText: @"抵扣的积分超过允许上限" bottomOffset:80];
break;
case 4004:
[PDToast showWithText: @"没有足够的积分用来抵扣" bottomOffset:80];
break;
case 4005:
[PDToast showWithText: @"找不到用户" bottomOffset:80];
break;
case 4006:
[PDToast showWithText: @"找不到商品" bottomOffset:80];
break;
case 4007:
[PDToast showWithText: @"已经支付的订单不能取消" bottomOffset:80];
break;
case 4008:
[PDToast showWithText: @"没有积分可以赠送" bottomOffset:80];
break;
case 4009:
[PDToast showWithText: @"领取积分失败" bottomOffset:80];
break;
case 4010:
[PDToast showWithText: @"积分点为0" bottomOffset:80];
break;
case 4011:
[PDToast showWithText: @"余额转出申请已经处理过了" bottomOffset:80];
break;
case 4012:
[PDToast showWithText: @"账户金额不足" bottomOffset:80];
break;
case 4013:
[PDToast showWithText: @"请不要重复申请" bottomOffset:180];
break;
case 4014:
[PDToast showWithText: @"请不要重复注册" bottomOffset:80];
break;
case 4015:
[PDToast showWithText: @"密码错误" bottomOffset:80];
break;
case 4016:
[PDToast showWithText: @"推荐商户数不够,申请客户经理失败" bottomOffset:80];
break;
case 4017:
[PDToast showWithText: @"当前时间段不能领积分" bottomOffset:80];
break;
case 4018:
[PDToast showWithText: @"不能自己做积分兑换" bottomOffset:80];
break;
case 4019:
[PDToast showWithText: @"申请已经处理过了" bottomOffset:80];
break;
case 4020:
[PDToast showWithText: @"该区域已经有区域经理了" bottomOffset:80];
break;
case 4021:
[PDToast showWithText: @"此手机号码不是商户" bottomOffset:80];
break;
case 4022:
[PDToast showWithText: @"该区域已经有区域经理了" bottomOffset:80];
break;
case 4023:
[PDToast showWithText: @"此用户已经是区域经理/客户经理" bottomOffset:80];
break;
case 4024:
[PDToast showWithText: @"手动领取积分功能还未开放" bottomOffset:80];
break;
case 4025:
[PDToast showWithText: @"获取验证码太频繁" bottomOffset:80];
break;
case 4026:
[PDToast showWithText: @"工资还未算出,不能查看" bottomOffset:80];
break;
case 4027:
[PDToast showWithText: @"当月工资已经支付过了" bottomOffset:80];
break;
default:
break;
}
}
基于这个类上面再次封装了一个Server类 专门处理接口的请求数据
Server0.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "HttpsRequest.h"
@interface Server0 : NSObject
+ (Server0 *)getInstance;
- (void)Register:(UIView *)SelfView :(NSMutableDictionary *)dic :(void(^)(id requsetStr))block;
- (void)Login:(UIView *)SelfView :(NSMutableDictionary *)dic :(void(^)(id requsetStr))block;
@end
#import "Server0.h"
@implementation Server0
+(instancetype)getInstance
{
static Server0 *server;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
server = [[Server0 alloc] init];
});
return server;
}
- (instancetype)init
{
self = [super init];
return self;
}
- (void)Register:(UIView *)SelfView :(NSMutableDictionary *)dic :(void(^)(id requsetStr))block{
//接口名
NSString *str = @"/user/register";
//Url
NSString *url = [NSString stringWithFormat:@"%@%@",NewReleaseURL,str];
//数据请求
[HttpsRequest getInstance].selfView = SelfView;
[[HttpsRequest getInstance] PUTData:dic :url andBlock:^(id requestStr) {
if ([[NSString stringWithFormat:@"%@",requestStr] isEqualToString:@"error"] || [[NSString stringWithFormat:@"%@",requestStr] isEqualToString:@"0"] ) {
block(0);
return;
}
else if([[NSString stringWithFormat:@"%@",requestStr] isEqualToString:@"1024"])
{
block(@"1024");
return;
}
else if([[NSString stringWithFormat:@"%@",requestStr] isEqualToString:@"2048"])
{
block(@"2048");
return;
}
else
{
NSLog(@"%@",requestStr);
block(requestStr);
}
}];
}
- (void)Login:(UIView *)SelfView :(NSMutableDictionary *)dic :(void(^)(id requsetStr))block{
//接口名
NSString *str = @"/user/login";
//Url
NSString *url = [NSString stringWithFormat:@"%@%@",NewReleaseURL,str];
//数据请求
[HttpsRequest getInstance].selfView = SelfView;
[[HttpsRequest getInstance] PostData:dic :url andBlock:^(id requestStr) {
if ([[NSString stringWithFormat:@"%@",requestStr] isEqualToString:@"error"] || [[NSString stringWithFormat:@"%@",requestStr] isEqualToString:@"0"] ) {
block(0);
return;
}
else if([[NSString stringWithFormat:@"%@",requestStr] isEqualToString:@"1024"])
{
block(@"1024");
return;
}
else if([[NSString stringWithFormat:@"%@",requestStr] isEqualToString:@"2048"])
{
block(@"2048");
return;
}
else
{
NSLog(@"%@",requestStr);
block(requestStr);
}
}];
}
@end
下面是具体的使用方法
Viewcontroller.m里面具体使用
#import "Server0.h"
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//登录
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:@"123456789" forKey:@"mobile"];
[dic setObject:@"123456" forKey:@"captcha"];
[self getLogin:dic];
//注册
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:@"123456" forKey:@"mobile"];
[dic setObject:@"123" forKey:@"captcha"];
[dic setObject:@"123455"forKey:@"referrerMobile"];
[self getRegister:dic];
NSLog(@"%@ %@",phone,verCode);
}
- (void)getLogin:(NSMutableDictionary *)dic{
[[Server0 getInstance] Login:self.view :dic :^(id requsetStr) {
if (requsetStr == 0)
{
}
else
{
NSLog(@"%@",requsetStr);
[UICKeyChainStore setString:[NSString stringWithFormat:@"%@",requsetStr[@"flag"]] forKey:@"flag" service:keychainValue];
[UICKeyChainStore setData:requsetStr[@"pages"] forKey:@"pages" service:keychainValue];
[UICKeyChainStore setString:[NSString stringWithFormat:@"%@",requsetStr[@"sessionID"]] forKey:@"sessionID" service:keychainValue];
[UICKeyChainStore setString:@"LoginSucceed" forKey:@"Login" service:keychainValue];
}
}];
}
- (void)getRegister:(NSMutableDictionary *)dic{
//dic为入参的参数结构体
[[Server0 getInstance] Register:self.view :dic :^(id requsetStr) {
if (requsetStr == 0)
{
}
else
{
NSLog(@"%@",requsetStr);
[UICKeyChainStore setString:[NSString stringWithFormat:@"%@",requsetStr[@"flag"]] forKey:@"flag" service:keychainValue];
[UICKeyChainStore setData:requsetStr[@"pages"] forKey:@"pages" service:keychainValue];
[UICKeyChainStore setString:[NSString stringWithFormat:@"%@",requsetStr[@"sessionID"]] forKey:@"sessionID" service:keychainValue];
[UICKeyChainStore setString:@"LoginSucceed" forKey:@"Login" service:keychainValue];
}
}];
}
这里我只列出了几个常用的方法,具体数据处理还要看自己对应的需求
requsetStr我自己做了一点处理 请求数据返回的数据里面如果有data为key的数据,会自动解析返回data对应的value值,所以requsetStr不同的接口返回的可能是字典也可能是数组!
如果大家有什么看不明白的地方可以留言给我!空一点我会写一个demo放到我的github上去!可能会更详细!
感谢大家的支持,我会继续努力为大家带来更多更好的开发上面的分享!
网友评论