美文网首页iOS点点滴滴
AFNetworking的简单封装

AFNetworking的简单封装

作者: _Waiting_ | 来源:发表于2017-11-20 18:27 被阅读70次

AFNetworking下载地址:

AFNetworking

1.导入AFNetworking文件

2.实现的功能

  • 监测网络
  • 对AFNetworking进行了二次封装
  • 简化了调用的代码

3.直接上代码啦

.h文件声明

//
//  HttpRequest.h
//  Test
//
//  Created by 123 on 2017/11/20.
//  Copyright © 2017年 123. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "HttpRequestHeader.h"
#import "AFNetworking.h"
#import "CSGetVCodeModel.h"
#import "CSRegisterModel.h"


typedef void (^ CSProgress)(NSProgress * _Nonnull) ;
typedef void (^ CSModelBlock)(id  _Nullable);

@interface HttpRequest : NSObject

/**
 网络请求单例

 @return 网络请求对象
 */
+(instancetype _Nullable )ShareRequest;

/**
 检查网络
 */
- (void)checkNetwork;

/**
 得到验证码

 @param phone 电话号码
 @param modelBlock 返回验证码类型
 */
- (void)getVCodeWithPhone:(NSString *_Nullable)phone
                 success:(void (^_Nullable)(CSGetVCodeModel *_Nullable))modelBlock;

/**
 注册

 @param phone 电话号码
 @param vcode 验证码
 @param sqn 流水号
 @param modelBlock 返回注册类型
 */
- (void)registerWithPhone:(NSString *_Nullable)phone
                    vcode:(NSString *_Nullable)vcode
                      sqn:(NSString *_Nullable)sqn
                 success:(void (^_Nullable)(CSRegisterModel *_Nullable))modelBlock;
@end

.m文件实现

//
//  HttpRequest.m
//  Test
//
//  Created by 123 on 2017/11/20.
//  Copyright © 2017年 123. All rights reserved.
//

#import "HttpRequest.h"
#import "MBProgressHUD.h"



@interface HttpRequest()
@property (nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
@property (nonatomic, strong) AFHTTPSessionManager *HTTPManager;
@property (nonatomic, copy) CSModelBlock modBlock ;
@end

@implementation HttpRequest
//单例
+(instancetype)ShareRequest
{
    static HttpRequest *request = nil;
    if (!request)
    {
        request = [[HttpRequest alloc] init];
    }
    [request initAFNetworking];
    return request;
}
- (void)initAFNetworking
{
    _HTTPManager = nil;
    if (!_HTTPManager)
    {
        _HTTPManager  = [AFHTTPSessionManager manager];
        _HTTPManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript", nil];
        
        _HTTPManager.requestSerializer = [AFJSONRequestSerializer serializer];
        
        _HTTPManager.responseSerializer = [AFJSONResponseSerializer serializer];
    }
    
    
    _reachabilityManager = nil;
    
    if (!_reachabilityManager)
    {
        _reachabilityManager = [AFNetworkReachabilityManager manager];
    }
    
}
//检查网络状态
- (void)checkNetwork
{
    
    __weak typeof(self) this = self;
    [_reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /*
         AFNetworkReachabilityStatusUnknown          = -1,
         AFNetworkReachabilityStatusNotReachable     = 0,
         AFNetworkReachabilityStatusReachableViaWWAN = 1,
         AFNetworkReachabilityStatusReachableViaWiFi = 2,
         */
        switch (status)
        {
            case AFNetworkReachabilityStatusUnknown:
                [this MBProgressHUDWithText:@"你现在使用的未知网络"];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [this MBProgressHUDWithText:@"网络不可用"];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [this MBProgressHUDWithText:@"你现在使用的流量"];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [this MBProgressHUDWithText:@"你现在使用的wifi"];
                break;
            default:
                break;
        }
    }];
    [_reachabilityManager startMonitoring];
}


- (void)getVCodeWithPhone:(NSString *_Nullable)phone
                  success:(void (^_Nullable)(CSGetVCodeModel *_Nullable))vcodeModel
{
    
    self.modBlock = ^(id _Nullable modelBlock)
    {
        NSDictionary *dic = (NSDictionary *)modelBlock;
        CSGetVCodeModel *model = [[CSGetVCodeModel alloc] initWithDictionary:dic];
        model.code = dic[@"msg"];
        model.sqn = dic[@"sqn"];
        model.vcode = dic[@"vcode"];
        vcodeModel(model);
    };
    [self postWithUrl:VCode parameters:@{@"mobile":phone}];
}

- (void)registerWithPhone:(NSString *_Nullable)phone
                    vcode:(NSString *_Nullable)vcode
                      sqn:(NSString *_Nullable)sqn
                  success:(void (^_Nullable)(CSRegisterModel *_Nullable))regBlock
{
    self.modBlock = ^(id _Nullable modelBlock) {
         NSDictionary *dic = (NSDictionary *)modelBlock;
        CSRegisterModel *model = [[CSRegisterModel alloc] initWithDictionary:dic];
        model.expire = dic[@"expire"];
        model.personID = dic[@"personID"];
        model.token = dic[@"token"];
        regBlock(model);
    };
    [self postWithUrl:Register parameters:@{@"mobile":phone,@"vcode":vcode,@"sqn":sqn}];
}




- (void)postWithUrl:(NSString *)url parameters:(NSDictionary *)parameters
{
    __weak typeof(self) this = self;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [_HTTPManager POST:[NSString stringWithFormat:@"%@%@",BaseUrl,url] parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            [this MBProgressHUDWithProgress:uploadProgress.fractionCompleted];
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSArray *arr = [dic allKeys];
            
            if ([arr containsObject:@"msg"])
            {
                [this MBProgressHUDWithText:dic[@"msg"]];
            }
            else
            {
                self.modBlock(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }); 
}


//显示
- (void)MBProgressHUDWithText:(NSString *)text
{
    MBProgressHUD *hud = nil;
    if (!hud)
    {
        hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    }
    hud.mode = MBProgressHUDModeText;
    hud.label.text = text;
    [hud hideAnimated:YES afterDelay:0.5];
    
}
//显示
- (void)MBProgressHUDWithProgress:(CGFloat)progress
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        MBProgressHUD *hud = nil;
        if (!hud)
        {
            hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
            hud.mode = MBProgressHUDModeDeterminate;
            hud.label.text = @"Loading...";
        }
        hud.progress = progress;
        if (progress == 1)
        {
            [hud hideAnimated:YES];
        }
    });
    
}
@end


相关文章

网友评论

    本文标题:AFNetworking的简单封装

    本文链接:https://www.haomeiwen.com/subject/fdfbvxtx.html