- AFNetworking是一個(gè)輕量級(jí)的iOS網(wǎng)絡(luò)通信類庫
- 它建立在NSURLConnection和NSOperation等類庫的基礎(chǔ)上摊趾,讓很多網(wǎng)絡(luò)通信功能的實(shí)現(xiàn)變得十分簡(jiǎn)單。
- NSURLConnection是處理網(wǎng)絡(luò)連接的游两。
- NSOperation是管理NSURLConnection的砾层,可以監(jiān)視一個(gè)請(qǐng)求的生命周期。
- AFURLConnectionOperation:NSOperation的子類贱案,實(shí)現(xiàn)了NSURLConnection 的代理方法肛炮。
- AFHTTPRequestOperation:AFURLConnectionOperation的子類,針對(duì)request使用的協(xié)議為HTTP和HTTPS宝踪。
- AFHTTPRequestOperationManager:封裝了一組調(diào)用請(qǐng)求的方法侨糟。
- 它支持HTTP請(qǐng)求和基于REST的網(wǎng)絡(luò)服務(wù)(包括GET、POST瘩燥、 PUT秕重、DELETE等)。
- 支持ARC厉膀。
AFNetworking3.0目前使用NSURLSession作為網(wǎng)絡(luò)類
對(duì)于iOS7.0以上的系統(tǒng)溶耘,AFNetworking提供了更高級(jí)的方法:
1.
AFURLSessionManager
:創(chuàng)建、管理基于NSURLSessionConfiguration
對(duì)象的NSURLSession
對(duì)象的類服鹅,也可以管理 session 的數(shù)據(jù)凳兵、下載/上傳任務(wù),實(shí)現(xiàn) session 和其相關(guān)聯(lián)的任務(wù)的 delegate 方法企软。
2.AFHTTPSessionManager
:封裝了一組調(diào)用請(qǐng)求的方法庐扫。
- AFNetworking可以檢測(cè)當(dāng)前網(wǎng)絡(luò)的可達(dá)性。
AFNetworkReachabilityManager:這個(gè)類監(jiān)控當(dāng)前網(wǎng)絡(luò)的可達(dá)性澜倦,提供回調(diào) block 和 notificaiton聚蝶,在可達(dá)性變化時(shí)調(diào)用。
- AFNetworking提供了請(qǐng)求的安全策略藻治。
AFSecurityPolicy:評(píng)估服務(wù)器對(duì)安全連接針對(duì)指定的固定證書或公共密鑰的信任碘勉。將你的服務(wù)器證書添加到 app bundle,以幫助防止 中間人攻擊桩卵。
下面是一些基礎(chǔ)例子:(先導(dǎo)入AFNetworking頭文件)
#pragma mark--------------GET 請(qǐng)求------------
-(void)GET{
//創(chuàng)建manager請(qǐng)求對(duì)象
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
[mgr GET:@"http://api.douban.com/v2/event/list?type=all&district=all&loc=108288&photo_cate=image&photo_count=1&start=3&day_type=future&apikey=062bcf31694a52d212836d943bdef876" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//responseObject里面,是請(qǐng)求成功以后里邊返回的字典或者數(shù)據(jù),對(duì)其進(jìn)行解析
NSLog(@"GET請(qǐng)求成功:%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"GET請(qǐng)求失敗:%@",error);
}];
}
- (void)POST{
//創(chuàng)建manager請(qǐng)求對(duì)象
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//設(shè)置請(qǐng)求的參數(shù)為json格式
mgr.requestSerializer = [AFJSONRequestSerializer serializer];
//設(shè)置響應(yīng)序列化為二進(jìn)制
mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
//設(shè)置body
NSDictionary *dic = @{@"date":@"20131129",@"startRecord":@"1",@"len":@"5",@"udid":@"1234567890",@"terminalType":@"Iphone",@"cid":@"213"};
[mgr POST:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"POST請(qǐng)求成功:%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"POST請(qǐng)求失敗:%@",error);
}];
}
注意網(wǎng)絡(luò)請(qǐng)求時(shí)要在info.plist文件里加下面的字段
添加的字段.png
#pragma mark-----文件下載-----
- (void)downLoad{
//創(chuàng)建一個(gè)用來分別配置每一個(gè)session對(duì)象的類,defaultSessionConfiguration:是session的默認(rèn)配置,使用硬盤來存儲(chǔ)緩存數(shù)據(jù)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//創(chuàng)建manager管理對(duì)象
AFURLSessionManager *mgr = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
//下載內(nèi)容的接口
NSURL *url = [NSURL URLWithString:@"http://tj-ctfs.ftn.qq.com/ftn_handler/0c5aea356cbf0c529934369eeabc80d78816ad7059a33ac2e20eaeb88273827d03be89e38025aa8dbdcc2227520993804054d97b81307ceea3ad6ed9982ec64c/AFN+SDW.key"];
//創(chuàng)建請(qǐng)求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//創(chuàng)建下載任務(wù)
NSURLSessionDownloadTask *task = [mgr downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
//該block需要返回值
NSURL *path = [[NSFileManager defaultManager]URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
//返回和服務(wù)器文件名一樣,當(dāng)我們希望保存 的文件和服務(wù)器的文件名一致時(shí),可以使用這個(gè)名字:suggestedFilename
return [path URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//打印下載后的存儲(chǔ)路徑
NSLog(@"文件下載路徑%@",filePath);
}];
[task resume];
}
#pragma mark-------文件上傳-------
- (void)upload{
//創(chuàng)建一個(gè)用來分別配置每一個(gè)session對(duì)象的類,defaultSessionConfiguration:是session的默認(rèn)配置,使用硬盤來存儲(chǔ)緩存數(shù)據(jù)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//創(chuàng)建manager管理對(duì)象
AFURLSessionManager *mgr = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
//上傳內(nèi)容的接口
NSURL *url = [NSURL URLWithString:@"http://tj-ctfs.ftn.qq.com/ftn_handler/0c5aea356cbf0c529934369eeabc80d78816ad7059a33ac2e20eaeb88273827d03be89e38025aa8dbdcc2227520993804054d97b81307ceea3ad6ed9982ec64c/AFN+SDW.key"];
//創(chuàng)建請(qǐng)求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//創(chuàng)建將要上傳文件的路徑
NSURL *path = [NSURL fileURLWithPath:@""];
//創(chuàng)建上傳任務(wù)
NSURLSessionUploadTask *task = [mgr uploadTaskWithRequest:request fromFile:path progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"上傳失敗-----%@",error);
}else{
NSLog(@"上傳成功-----%@------%@",response,responseObject);
}
}];
[task resume];
}
#pragma mark-----網(wǎng)絡(luò)判斷---------------
- (void)reachbility{
//創(chuàng)建網(wǎng)絡(luò)監(jiān)聽管理者對(duì)象
AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
[mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
NSLog(@"未識(shí)別的網(wǎng)絡(luò)");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"2G,3G,4G網(wǎng)絡(luò)");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"wifi網(wǎng)絡(luò)");
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"未連接的網(wǎng)絡(luò)");
break;
default:
break;
}
}];
//開啟監(jiān)聽
[mgr startMonitoring];
}