AF3.0封裝(MB管理集成)

隨著ipv6的使用,AFNetWoring發(fā)布了3.0版本滤祖,剛剛完成的這個(gè)項(xiàng)目我用的是AF3.0筷狼,這里有這次使用AF3.0的封裝,簡單說一下都是怎么做的匠童。

1.單例形式創(chuàng)建AFHTTPSessionManager的子類埂材。

+ (instancetype)sharedClient {
    static AFAppDotNetAPIClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[AFAppDotNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:AFAppDotNetAPIBaseURLString]];
        _sharedClient.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
        _sharedClient.requestSerializer.timeoutInterval = 30;     // 設(shè)置超時(shí)時(shí)間30s
        
        //支持https,SSL證書加密
//        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//        securityPolicy.allowInvalidCertificates = YES;
//        securityPolicy.validatesDomainName = NO;
//        _sharedClient.securityPolicy = securityPolicy;
    });
    return _sharedClient;
}

2.封裝基本通用的請(qǐng)求方法

.h接口文件

/**
 *  返回json結(jié)構(gòu)為CommenReturnModel的HTTP請(qǐng)求
 *
 *  @param parameters 參數(shù)集汤求,為#NSDictionary#類型
 *  @param POST       地址俏险,除BaseUrl之外的部分
 *  @param block      block參數(shù)
 *
 *  @return           返回值
 */

+(NSURLSessionDataTask*)normalHttpRequestWithParameters:(NSDictionary*)parameters POST:(NSString*)POST resultBlock:(void(^)(NSDictionary* commentReturnModel, NSError*error))block;
/*!
 *  上傳圖片接口
 *
 *  @param parameters 參數(shù)集,為#NSDictionary#類型
 *  @param picDic     圖片字典{key為推薦命名扬绪。value為圖片}
 *  @param POST       地址竖独,除BaseUrl之外的部分
 *  @param block      block參數(shù)
 *
 *  @return           返回值
 */
+(NSURLSessionDataTask*)uploadHttpRequestWithParameters:(NSDictionary*)parameters PictureDic:(NSDictionary *)picDic POST:(NSString*)POST resultBlock:(void(^)(NSDictionary* commentReturnModel, NSError*error))block;

.m實(shí)現(xiàn)文件

//返回json結(jié)構(gòu)為CommenReturnModel的HTTP請(qǐng)求
+(NSURLSessionDataTask*)normalHttpRequestWithParameters:(NSDictionary *)parameters POST:(NSString *)POST resultBlock:(void (^)(NSDictionary *, NSError *))block{
    DEBUGLog(@"%@%@?%@",AFAppDotNetAPIBaseURLString, POST, [self getStringWithDictionary:parameters]);
    dispatch_async(dispatch_get_main_queue(), ^{
        [[MbprogressTool standard] showprogressHUD];
    });
    NSString * post = [NSString stringWithFormat:@"%@%@",AFAppDotNetAPIBaseURLString,POST];
    return [[AFAppDotNetAPIClient sharedClient] POST:post parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DEBUGLog(@"%@",responseObject);
        NSAssert([responseObject isKindOfClass:[NSDictionary class]], @"JSON結(jié)構(gòu)返回與約定不符");
        if (block) {
            block(responseObject, nil);
        }
        [[MbprogressTool standard] hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (block) {
            block(nil, error);
        }
        [[MbprogressTool standard] hiddenProgressHUD];
    }];
}

//圖片上傳
+(NSURLSessionDataTask *)uploadHttpRequestWithParameters:(NSDictionary *)parameters PictureDic:(NSDictionary *)picDic POST:(NSString *)POST resultBlock:(void (^)(NSDictionary *, NSError *))block{
    NSString * post = [NSString stringWithFormat:@"%@%@",AFAppDotNetAPIBaseURLString,POST];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[MbprogressTool standard] showprogressHUD];
    });
    return [[AFAppDotNetAPIClient sharedClient] POST:post parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSString *keyString in [picDic allKeys]){
            NSData *imgData = [picDic objectForKey:keyString];
            if (imgData.length > 0) {
                [formData appendPartWithFileData:imgData name:keyString fileName:[NSString stringWithFormat:@"%@%u.jpg", keyString,arc4random()%98] mimeType:@"image/jpeg"];
                DEBUGLog(@"圖片上傳%@",keyString);
            }
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DEBUGLog(@"%@",parameters);
        NSAssert([responseObject isKindOfClass:[NSDictionary class]], @"JSON結(jié)構(gòu)返回與約定不符");
        if (block) {
            block(responseObject, nil);
        }
        [[MbprogressTool standard] hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (block) {
            block(nil, error);
        }
        [[MbprogressTool standard] hiddenProgressHUD];
    }];
}

3.具體接口再次對(duì)通用接口進(jìn)行封裝(嫌麻煩的話直接用通用的也可以)

我這里是用對(duì)上面的通用接口類加不同的擴(kuò)展實(shí)現(xiàn)的(下圖也是我的整個(gè)網(wǎng)絡(luò)部分結(jié)構(gòu))

接口邏輯.png

一個(gè)具體的實(shí)現(xiàn)例子

/*!
 *  查詢收藏列表
 *
 *  @param currectPage 當(dāng)前頁面
 *  @param block       block description
 *
 *  @return return value description
 */
+(NSURLSessionDataTask*)getMyCollectListIsCurretPage:(NSInteger)currectPage ResultBlock:(void(^)(NSArray * model, NSString *failMessage))block;

+(NSURLSessionDataTask*) getMyCollectListIsCurretPage:(NSInteger)currectPage ResultBlock:(void(^)(NSArray * model, NSString *failMessage))block{
    NSDictionary * parma = @{@"userId":@"",
                             @"pageSize":@"10",
                             @"pageIndex":@(currectPage)};
    return [self normalHttpRequestWithParameters:parma POST:isBaby?MyCollectBabyListURL:MyCollectShowListURL resultBlock:^(NSDictionary *commentReturnModel, NSError *error) {
        if (!error){//成功是操作
            if ([[commentReturnModel objectForKey:@"status"] integerValue] == DEF_SUCESS_CODE){
                
                NSMutableArray * dataArr = [[NSMutableArray alloc]init];
                [commentReturnModel[@"data"][@"dataList"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (isBaby) {
                        MyCollectBabyModel * styleModel = [[MyCollectBabyModel alloc]initWithDictionary:obj];
                        [dataArr addObject:styleModel];
                    }else{
                        MyCollectShowBabyModel * styleModel = [[MyCollectShowBabyModel alloc]initWithDictionary:obj];
                        [dataArr addObject:styleModel];
                    }
                }];
                NSArray * model = [NSArray arrayWithArray:dataArr];
                if (block) {
                    block(model, nil);
                }
            }
            else{//失敗時(shí)的操作
                if (block) {
                    block(nil, [commentReturnModel objectForKey:@"msg"]);
                }
            }
        }else{//錯(cuò)誤時(shí)的操作
            if (block) {
                block(nil, @"網(wǎng)絡(luò)請(qǐng)求失敗");
            }
        }
    }];
}

上面就是我的AF的封裝其中還有兩個(gè)類說一下

1.NetRequestUrls 這里我是存放了所有的接口地址,這樣方便統(tǒng)一管理挤牛,

2.MbprogressTool則是對(duì)于MB的一個(gè)封裝

在上面通用方法的時(shí)候大家應(yīng)該發(fā)現(xiàn)了我在開始請(qǐng)求的時(shí)候調(diào)用了一下莹痢,在結(jié)束是停止,這樣就可以買一個(gè)請(qǐng)求都有MB了不用在所有地方都寫墓赴。MbprogressTool具體實(shí)現(xiàn)如下:

.h接口文件

#import <Foundation/Foundation.h>

@interface MbprogressTool : NSObject
+(instancetype)standard;
-(void)showprogressHUD;
-(void)hiddenProgressHUD;
-(UIViewController *)getCurrentVC;
@end

.m實(shí)現(xiàn)文件

#import "MbprogressTool.h"
#import <MBProgressHUD.h>
#import <UIImage+GIF.h>

@interface MbprogressTool ()
@property (nonatomic, strong) MBProgressHUD *progressHUD;
@property (nonatomic, assign) NSInteger referenceCount;//引用mb的個(gè)數(shù)
@end

@implementation MbprogressTool
+(instancetype)standard{
    static MbprogressTool *mbprogressTool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mbprogressTool = [[MbprogressTool alloc] init];
        mbprogressTool.progressHUD = [[MBProgressHUD alloc]init];
        mbprogressTool.progressHUD.color = [UIColor clearColor];
        mbprogressTool.progressHUD.mode = MBProgressHUDModeCustomView;
        UIImageView * imageView = [[UIImageView alloc]initWithImage:[UIImage sd_animatedGIFNamed:@"刷新gif"]];
        imageView.layer.cornerRadius = 15;
        imageView.layer.masksToBounds = YES;
        imageView.alpha = 0.7;
        imageView.frame = CGRectMake(0, 0, 123/1.5, 123/1.5);
        mbprogressTool.progressHUD.customView = imageView;
        mbprogressTool.progressHUD.removeFromSuperViewOnHide = YES;
        //mbprogressTool.progressHUD.labelText=@"加載中...";
        //mbprogressTool.progressHUD.labelFont = DEF_STFont(14.0);
        
        mbprogressTool.referenceCount = 0;
    });
    return mbprogressTool;
}

-(void)showprogressHUD{
    _referenceCount++;
    if ([self getCurrentVC].navigationController != nil) {
        [[self getCurrentVC].navigationController.view addSubview:_progressHUD];
    }else{
        [[self getCurrentVC].view addSubview:_progressHUD];
    }
    [_progressHUD show:YES];
}

-(void)hiddenProgressHUD{
    _referenceCount--;
    if (_referenceCount == 0) {
        [_progressHUD hide:YES];
    }
//    [_progressHUD removeFromSuperview];
}

//獲取當(dāng)前屏幕顯示的viewcontroller
-(UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal){
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows){
            if (tmpWin.windowLevel == UIWindowLevelNormal){
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *View = [[window subviews] objectAtIndex:0];
    UIView *frontView = [[View subviews] lastObject];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]]){
        result = nextResponder;
    }
    else{
        result = window.rootViewController;
    }
    return result;
}

@end

寫完了竞膳,因?yàn)楝F(xiàn)在完成的這個(gè)項(xiàng)目就是用的這套東西所以使用起來應(yīng)該沒有問題,有什么問題可以問我诫硕,坦辟,,

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末章办,一起剝皮案震驚了整個(gè)濱河市锉走,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌藕届,老刑警劉巖挪蹭,帶你破解...
    沈念sama閱讀 218,640評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異翰舌,居然都是意外死亡嚣潜,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門椅贱,熙熙樓的掌柜王于貴愁眉苦臉地迎上來懂算,“玉大人只冻,你說我怎么就攤上這事〖萍迹” “怎么了喜德?”我有些...
    開封第一講書人閱讀 165,011評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長垮媒。 經(jīng)常有香客問我舍悯,道長,這世上最難降的妖魔是什么睡雇? 我笑而不...
    開封第一講書人閱讀 58,755評(píng)論 1 294
  • 正文 為了忘掉前任萌衬,我火速辦了婚禮,結(jié)果婚禮上它抱,老公的妹妹穿的比我還像新娘秕豫。我一直安慰自己,他們只是感情好观蓄,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,774評(píng)論 6 392
  • 文/花漫 我一把揭開白布混移。 她就那樣靜靜地躺著,像睡著了一般侮穿。 火紅的嫁衣襯著肌膚如雪歌径。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,610評(píng)論 1 305
  • 那天亲茅,我揣著相機(jī)與錄音回铛,去河邊找鬼。 笑死克锣,一個(gè)胖子當(dāng)著我的面吹牛勺届,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播娶耍,決...
    沈念sama閱讀 40,352評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼饼酿!你這毒婦竟也來了榕酒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,257評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤故俐,失蹤者是張志新(化名)和其女友劉穎想鹰,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體药版,經(jīng)...
    沈念sama閱讀 45,717評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡辑舷,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,894評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了槽片。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片何缓。...
    茶點(diǎn)故事閱讀 40,021評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡肢础,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出碌廓,到底是詐尸還是另有隱情传轰,我是刑警寧澤,帶...
    沈念sama閱讀 35,735評(píng)論 5 346
  • 正文 年R本政府宣布谷婆,位于F島的核電站慨蛙,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏纪挎。R本人自食惡果不足惜期贫,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,354評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望异袄。 院中可真熱鬧通砍,春花似錦、人聲如沸隙轻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽玖绿。三九已至敛瓷,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間斑匪,已是汗流浹背呐籽。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評(píng)論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蚀瘸,地道東北人狡蝶。 一個(gè)月前我還...
    沈念sama閱讀 48,224評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像贮勃,于是被迫代替她去往敵國和親贪惹。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,974評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,156評(píng)論 25 707
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理寂嘉,服務(wù)發(fā)現(xiàn)奏瞬,斷路器,智...
    卡卡羅2017閱讀 134,657評(píng)論 18 139
  • 國家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報(bào)批稿:20170802 前言: 排版 ...
    庭說閱讀 10,975評(píng)論 6 13
  • 今天該寫些什么呢?今天就說說在寫作群里認(rèn)識(shí)的楊子姐姐寓搬。 她整個(gè)人的精氣神帶給我很大的震撼珍昨。她的年紀(jì)應(yīng)該到了五十知天...
    陳蓁蓁閱讀 364評(píng)論 0 1
  • 末日來臨的那天,人類在廢墟中央砌上了高墻,大門外是成群的僵尸在游蕩镣典。不名火燃燒大大小小的車輛兔毙,我獨(dú)自,獨(dú)自地骆撇,生活...
    iankymic閱讀 385評(píng)論 0 0