AFNetworking 3.0

小小感言
本來是想寫博客來著阿迈,朋友說簡書的排版更好些畏陕,于是就來試試。
總想著把自己開發(fā)中遇到的技術(shù)點(diǎn)仿滔、問題還有大大小小的坑都總結(jié)出來惠毁,但就是一直沒有時(shí)間寫,或者可能是自己沒有養(yǎng)成寫的好習(xí)慣并堅(jiān)持下去吧崎页,平常也就是在備忘錄鞠绰、文檔里那么隨便一記,以后得好好改進(jìn)了飒焦。
這篇文章我就總結(jié)一下自己網(wǎng)絡(luò)請(qǐng)求和上傳數(shù)據(jù)的時(shí)候用到的afn3.0
AFNetworking 介紹
AFNetworking 1.0是建立在NSURLConnection的基礎(chǔ)API上的 蜈膨,AFNetworking 2.0開始使用NSURLConnection的基礎(chǔ)API ,以及較新基于NSURLSession的API的選項(xiàng)牺荠。 AFNetworking 3.0現(xiàn)已完全基于NSURLSession的API翁巍,這降低了維護(hù)的負(fù)擔(dān),同時(shí)支持蘋果增強(qiáng)關(guān)于NSURLSession提供的任何額外功能休雌。由于Xcode 7中灶壶,NSURLConnection的API已經(jīng)正式被蘋果棄用。雖然該API將繼續(xù)運(yùn)行杈曲,但將沒有新功能將被添加驰凛,并且蘋果已經(jīng)通知所有基于網(wǎng)絡(luò)的功能胸懈,以充分使NSURLSession向前發(fā)展。
AFNetworking 3.0正式支持的iOS 7恰响, Mac OS X的10.9趣钱, watchOS 2 , tvOS 9 和Xcode 7胚宦。
在AFNetworking3.0中下面這些類已被廢棄:

  • AFURLConnectionOperation
  • AFHTTPRequestOperation
  • AFHTTPRequestOperationManager

另外這些類包含基于NSURLConnection的API的內(nèi)部實(shí)現(xiàn)首有,他們已經(jīng)被使用NSURLSession重構(gòu):

  • UIImageView+AFNetworking
  • UIWebView+AFNetworking
  • UIButton+AFNetworking

Post請(qǐng)求

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval= 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js", nil];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy = securityPolicy;
[manager POST:urlStr parameters:dic success:^(NSURLSessionTask *task, id responseObject) {
     NSLog(@"請(qǐng)求成功");
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"%@ error" , error);
    }];

Get請(qǐng)求

因?yàn)轫?xiàng)目里用到的都是post請(qǐng)求,get請(qǐng)求我就簡單的附上

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 
[manager GET:URL parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) { 
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {

      NSLog(@"請(qǐng)求成功");
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
      NSLog(@"%@",error); 
}];

上傳圖片

-(void)PostUploadImage:(NSMutableDictionary*)dic Url:(NSString *)url
{
    UIImage *image = [dic valueForKey:@"pic"];//圖片以鍵值對(duì)的形式存為了一個(gè)字典
    NSData *data =UIImageJPEGRepresentation(image , 0.5);
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    [request setHTTPMethod:@"POST"];    
    [request setHTTPBody:data];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"%@error" , error);
        }else{
            NSString *str = [[ NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *dic = [ NSDictionary dictionary];
            dic = [self dictionaryWithJsonString:str];
            self.Block(dic);//返回?cái)?shù)據(jù)
        }
    }];
    [dataTask resume];
}
-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
        return nil;
    }
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
if(err) {
        NSLog(@"json解析失斒嗳啊:%@",err);
        return nil;
    }
    return dic;
}

上傳多張圖片

-(void)POSTuploadImages:(NSArray*)imageArray url:(NSString*)url
{
    NSError* error = NULL;
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        for (int i = 0; i<imageArray.count; i++) {
            
                        NSData *uploadImage = imageArray[i];//數(shù)組里存儲(chǔ)的已經(jīng)將UIImage轉(zhuǎn)化為了NSData
                        // 上傳的參數(shù)名
                        NSString * Name = [NSString stringWithFormat:@"%d",i+1];
                        // 上傳filename
                        NSString * fileName = [NSString stringWithFormat:@"%@.png", Name];
                        [formData appendPartWithFileData:uploadImage name:Name fileName:fileName mimeType:@"image/png"];
                    }
    } error:&error];
    
    // 可在此處配置驗(yàn)證信息
    
    // 將 NSURLRequest 與 completionBlock 包裝為 NSURLSessionUploadTask
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionUploadTask *uploadTask =[manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                NSString *str = [[ NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSDictionary *dic = [ NSDictionary dictionary];
                dic = [self dictionaryWithJsonString:str];
              NSLog(@"%@===========",dic);//最終的數(shù)據(jù)
                self.Block(dic);//使用block返回?cái)?shù)據(jù)
    }];                                      
}

上傳錄音文件

-(void)POSTuploadSound:(NSMutableDictionary*)dic url:(NSString*)url
{
    
    NSData *data= [dic valueForKey:@"Sound"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    [request setHTTPMethod:@"POST"];
    
    [request setHTTPBody:data];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"%@error" , error);
        }else{
            NSString *str = [[ NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *dic = [ NSDictionary dictionary];
            dic = [self dictionaryWithJsonString:str];
            self.Block(dic);
        }
    }];
    [dataTask resume];   
}

下載

-(void)downLoadUrl:(NSString *)url{ 
//1.創(chuàng)建管理者對(duì)象 
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 
//2.請(qǐng)求的URL地址 
NSURL *url = [NSURL URLWithString:url]; 
//3.創(chuàng)建請(qǐng)求對(duì)象 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
//下載任務(wù) 
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { 
//打印下下載進(jìn)度 
NSLog(@"%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
 } 
destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { 
//下載地址 
     NSLog(@"默認(rèn)下載地址:%@",targetPath); 
//設(shè)置下載路徑绞灼,通過沙盒獲取緩存地址,最后返回NSURL對(duì)象 NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; 
return [NSURL URLWithString:filePath];
 } 
completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { 
//下載完成調(diào)用的方法 
NSLog(@"下載完成"); 
NSLog(@"%@---------------%@",response,filePath); }]; 
//開始啟動(dòng)任務(wù)
 [task resume];
}

網(wǎng)絡(luò)監(jiān)聽

-(BOOL)isNetWorkReachable{
    AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [afNetworkReachabilityManager startMonitoring];  //開啟網(wǎng)絡(luò)監(jiān)視器呈野;
    
    [afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:{
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
                
                // 設(shè)置圖片
                hud.labelText = @"無網(wǎng)絡(luò) 低矮,請(qǐng)檢查網(wǎng)絡(luò)連接";
                // 再設(shè)置模式
                hud.mode = MBProgressHUDModeCustomView;
                hud.center = self.window.center;
                // 隱藏時(shí)候從父控件中移除
                hud.removeFromSuperViewOnHide = YES;
                
                // 2秒之后再消失
                [hud hide:YES afterDelay:2];
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:{
            NSLog(@"WiFi" );
                break;
            }
                
            case AFNetworkReachabilityStatusReachableViaWWAN:{
            NSLog(@"數(shù)據(jù)網(wǎng)絡(luò)" );
                break;
            }
            case AFNetworkReachabilityStatusUnknown:{
            NSLog(@"未知網(wǎng)絡(luò)" );
             break;
            }  
            default:
                break;
        }
        
    }];
    return [AFNetworkReachabilityManager sharedManager].isReachable;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市被冒,隨后出現(xiàn)的幾起案子军掂,更是在濱河造成了極大的恐慌,老刑警劉巖昨悼,帶你破解...
    沈念sama閱讀 216,544評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蝗锥,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡率触,警方通過查閱死者的電腦和手機(jī)终议,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來葱蝗,“玉大人穴张,你說我怎么就攤上這事×铰” “怎么了皂甘?”我有些...
    開封第一講書人閱讀 162,764評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長悼凑。 經(jīng)常有香客問我偿枕,道長,這世上最難降的妖魔是什么户辫? 我笑而不...
    開封第一講書人閱讀 58,193評(píng)論 1 292
  • 正文 為了忘掉前任渐夸,我火速辦了婚禮,結(jié)果婚禮上渔欢,老公的妹妹穿的比我還像新娘墓塌。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,216評(píng)論 6 388
  • 文/花漫 我一把揭開白布桃纯。 她就那樣靜靜地躺著酷誓,像睡著了一般披坏。 火紅的嫁衣襯著肌膚如雪态坦。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,182評(píng)論 1 299
  • 那天棒拂,我揣著相機(jī)與錄音伞梯,去河邊找鬼。 笑死帚屉,一個(gè)胖子當(dāng)著我的面吹牛谜诫,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播攻旦,決...
    沈念sama閱讀 40,063評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼喻旷,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了牢屋?” 一聲冷哼從身側(cè)響起且预,我...
    開封第一講書人閱讀 38,917評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎烙无,沒想到半個(gè)月后锋谐,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,329評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡截酷,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,543評(píng)論 2 332
  • 正文 我和宋清朗相戀三年涮拗,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片迂苛。...
    茶點(diǎn)故事閱讀 39,722評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡三热,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出三幻,到底是詐尸還是另有隱情康铭,我是刑警寧澤,帶...
    沈念sama閱讀 35,425評(píng)論 5 343
  • 正文 年R本政府宣布赌髓,位于F島的核電站从藤,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏锁蠕。R本人自食惡果不足惜夷野,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,019評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望荣倾。 院中可真熱鬧悯搔,春花似錦、人聲如沸舌仍。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至灌曙,卻和暖如春菊碟,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背在刺。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評(píng)論 1 269
  • 我被黑心中介騙來泰國打工逆害, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蚣驼。 一個(gè)月前我還...
    沈念sama閱讀 47,729評(píng)論 2 368
  • 正文 我出身青樓魄幕,卻偏偏與公主長得像,于是被迫代替她去往敵國和親颖杏。 傳聞我的和親對(duì)象是個(gè)殘疾皇子纯陨,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,614評(píng)論 2 353

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