开源中国iOS客户端学习——(八)网络通信AFNetworking类库
AFNetworking是一個(gè)輕量級(jí)的iOS網(wǎng)絡(luò)通信類庫(kù),繼ASI類庫(kù)不在更新之后開(kāi)發(fā)者們有一套不錯(cuò)選擇;
AFNetworking類庫(kù)×××和使用教程:?https://github.com/AFNetworking/AFNetworking
如果想深入研究有官方文檔介紹:http://afnetworking.github.com/AFNetworking/
在開(kāi)源中國(guó)iOS客戶端中關(guān)于AFNetworking類庫(kù)的使用只用到了兩個(gè)實(shí)例方法
(1)getPath:parameters:success:failure:
(2)postPath:parameters:success:failure:
他們用法基本相同,只是請(qǐng)求數(shù)據(jù)方式不同,一種是Get請(qǐng)求和Post請(qǐng)求。Get是向服務(wù)器發(fā)索取數(shù)據(jù)的一種請(qǐng)求,也就相當(dāng)于查詢信息功能,不會(huì)修改類容,Post是向服務(wù)器提交數(shù)據(jù)的一種請(qǐng)求,影響數(shù)據(jù)內(nèi)容;兩種方法定義:
- (void)postPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters]; AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; [self enqueueHTTPRequestOperation:operation]; }
getPath:parameters:success:failure:方法在程序中使用舉例:
NewsView.m
- (void)reload:(BOOL)noRefresh { //如果有網(wǎng)絡(luò)連接 if ([Config Instance].isNetworkRunning) { if (isLoading || isLoadOver) { return; } if (!noRefresh) { allCount = 0; } int pageIndex = allCount/20; NSString *url; switch (self.catalog) { case 1: url = [NSString stringWithFormat:@"%@?catalog=%d&pageIndex=%d&pageSize=%d", api_news_list, 1, pageIndex, 20]; break; case 2: url = [NSString stringWithFormat:@"%@?type=latest&pageIndex=%d&pageSize=%d", api_blog_list, pageIndex, 20]; break; case 3: url = [NSString stringWithFormat:@"%@?type=recommend&pageIndex=%d&pageSize=%d", api_blog_list, pageIndex, 20]; break; } [[AFOSCClient sharedClient]getPath:url parameters:Nil success:^(AFHTTPRequestOperation *operation, id responseObject) { [Tool getOSCNotice2:operation.responseString]; isLoading = NO; if (!noRefresh) { [self clear]; } @try { NSMutableArray *newNews = self.catalog <= 1 ? [Tool readStrNewsArray:operation.responseString andOld: news]: [Tool readStrUserBlogsArray:operation.responseString andOld: news]; int count = [Tool isListOver2:operation.responseString]; allCount += count; if (count < 20) { isLoadOver = YES; } [news addObjectsFromArray:newNews]; [self.tableNews reloadData]; [self doneLoadingTableViewData]; //如果是第一頁(yè) 則緩存下來(lái) if (news.count <= 20) { [Tool saveCache:5 andID:self.catalog andString:operation.responseString]; } } @catch (NSException *exception) { [NdUncaughtExceptionHandler TakeException:exception]; } @finally { [self doneLoadingTableViewData]; } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"新聞列表獲取出錯(cuò)"); //如果是刷新 [self doneLoadingTableViewData]; if ([Config Instance].isNetworkRunning == NO) { return; } isLoading = NO; if ([Config Instance].isNetworkRunning) { [Tool ToastNotification:@"錯(cuò)誤 網(wǎng)絡(luò)無(wú)連接" andView:self.view andLoading:NO andIsBottom:NO]; } }]; isLoading = YES; [self.tableNews reloadData]; } //如果沒(méi)有網(wǎng)絡(luò)連接 else { NSString *value = [Tool getCache:5 andID:self.catalog]; if (value) { NSMutableArray *newNews = [Tool readStrNewsArray:value andOld:news]; [self.tableNews reloadData]; isLoadOver = YES; [news addObjectsFromArray:newNews]; [self.tableNews reloadData]; [self doneLoadingTableViewData]; } } }分析一下這里面的代碼:
首先是做一個(gè)網(wǎng)絡(luò)連接判斷,在開(kāi)源中國(guó)iOS客戶端學(xué)習(xí)——(六)網(wǎng)絡(luò)連接檢測(cè)一文中介紹了,作者并不是用這種方法來(lái)判斷,而是使用getPath:parameters:success:failure:來(lái)判斷網(wǎng)絡(luò)的連接,方法使用AFHTTPRequestOperation和“PATCH”請(qǐng)求HTTP客戶端操作隊(duì)列,使用到了block塊(iOS 4.0+特性),URL請(qǐng)求成功執(zhí)行success塊里操作,這里面block塊沒(méi)有返回值,接受兩個(gè)參數(shù),創(chuàng)建請(qǐng)求操作和響應(yīng)數(shù)據(jù)請(qǐng)求,URL請(qǐng)求失敗執(zhí)行failure里面的方法,這個(gè)block塊里仍沒(méi)有返回值,接受兩個(gè)參數(shù)創(chuàng)建請(qǐng)求操作和NSError對(duì)象,描述網(wǎng)絡(luò)或解析錯(cuò)誤狀況;
在?if()中的方法[Config Instance].isNetworkRunning==YES的,如果程序加載或者已經(jīng)加載完畢什么也不返回,如果程序沒(méi)有加載數(shù)據(jù),將數(shù)據(jù)列表數(shù)量顯示為0,接下來(lái)是在switch()中,根據(jù)使用者選擇設(shè)置不同API接口(下圖),然后就是解析顯示數(shù)據(jù)信息,顯示在視圖中;
??
在AFNetwork 文件夾中,作者自己添加了一個(gè)AFOSCClient類,該類繼承AFHTTPClient,又設(shè)計(jì)了一個(gè)sharedClient的類方法,從返回的結(jié)果可以推測(cè)出它是通過(guò)API請(qǐng)求返回json類型的數(shù)據(jù),具體什么作用還沒(méi)看出來(lái);
[Tool getOSCNotice2:operation.responseString];是封裝在在Tool類中的解析獲取的XML的文件
URL請(qǐng)求成功,還做了一個(gè)程序異常處理,防止請(qǐng)求數(shù)據(jù)過(guò)成功程序異常崩潰
?關(guān)于@try @catch @finally異常處理的使用:
{
//執(zhí)行的代碼,其中可能有異常。一旦發(fā)現(xiàn)異常,則立即跳到catch執(zhí)行。否則不會(huì)執(zhí)行catch里面的內(nèi)容
}
@catch
{
//除非try里面執(zhí)行代碼發(fā)生了異常,否則這里的代碼不會(huì)執(zhí)行
}
@finally
{
//不管什么情況都會(huì)執(zhí)行,包括try catch 里面用了return ,可以理解為只要執(zhí)行了try或者catch,就一定會(huì)執(zhí)行 finally
}
如果URL請(qǐng)求的數(shù)據(jù)出錯(cuò),則反應(yīng)網(wǎng)絡(luò)不連通,數(shù)據(jù)不能加載,則彈出GCDiscreetNotificationView提示視圖 ?提示網(wǎng)絡(luò)錯(cuò)誤;
postPath:parameters:success:failure:方法在程序中使用舉例:
FriendsView.m
-(void)reload:(BOOL)noRefresh { if (isLoadOver) { [self doneLoadingTableViewData]; return; } [[AFOSCClient sharedClient] postPath:api_friends_list parameters:[NSDictionary dictionaryWithObjectsAndKeys:segement.selectedSegmentIndex == 0 ? @"1" : @"0",@"relation", [NSString stringWithFormat:@"%d", friends.count/20],@"pageIndex", @"20",@"pageSize", [NSString stringWithFormat:@"%d", [Config Instance].getUID],@"uid",nil] success:^(AFHTTPRequestOperation *operation, id responseObject) { if (!noRefresh) { [self clear]; } [self doneLoadingTableViewData]; isLoading = NO; NSString *response = operation.responseString; [Tool getOSCNotice2:response]; @try { TBXML *xml = [[TBXML alloc] initWithXMLString:response error:nil]; TBXMLElement *root = xml.rootXMLElement; //顯示 TBXMLElement *_friends = [TBXML childElementNamed:@"friends" parentElement:root]; if (!_friends) { isLoadOver = YES; [self.tableFriends reloadData]; return; } TBXMLElement *first = [TBXML childElementNamed:@"friend" parentElement:_friends]; if (first == nil) { [self.tableFriends reloadData]; isLoadOver = YES; return; } NSMutableArray *newFriends = [[NSMutableArray alloc] initWithCapacity:20]; TBXMLElement *name = [TBXML childElementNamed:@"name" parentElement:first]; TBXMLElement *userid = [TBXML childElementNamed:@"userid" parentElement:first]; TBXMLElement *portrait = [TBXML childElementNamed:@"portrait" parentElement:first]; TBXMLElement *expertise = [TBXML childElementNamed:@"expertise" parentElement:first]; TBXMLElement *gender = [TBXML childElementNamed:@"gender" parentElement:first]; Friend *f = [[Friend alloc] initWithParameters:[TBXML textForElement:name] andUID:[[TBXML textForElement:userid] intValue] andPortrait:[TBXML textForElement:portrait] andExpertise:[TBXML textForElement:expertise] andMale:[[TBXML textForElement:gender] intValue] == 1]; if (![Tool isRepeatFriend: friends andFriend:f]) { [newFriends addObject:f]; } while (first) { first = [TBXML nextSiblingNamed:@"friend" searchFromElement:first]; if (first) { name = [TBXML childElementNamed:@"name" parentElement:first]; userid = [TBXML childElementNamed:@"userid" parentElement:first]; portrait = [TBXML childElementNamed:@"portrait" parentElement:first]; expertise = [TBXML childElementNamed:@"expertise" parentElement:first]; gender = [TBXML childElementNamed:@"gender" parentElement:first]; f = [[Friend alloc] initWithParameters:[TBXML textForElement:name] andUID:[[TBXML textForElement:userid] intValue] andPortrait:[TBXML textForElement:portrait] andExpertise:[TBXML textForElement:expertise] andMale:[[TBXML textForElement:gender] intValue] == 1]; if (![Tool isRepeatFriend:friends andFriend:f]) { [newFriends addObject:f]; } } else break; } if (newFriends.count < 20) { isLoadOver = YES; } [friends addObjectsFromArray:newFriends]; [self.tableFriends reloadData]; } @catch (NSException *exception) { [NdUncaughtExceptionHandler TakeException:exception]; } @finally { [self doneLoadingTableViewData]; } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"好友列表獲取出錯(cuò)"); [self doneLoadingTableViewData]; isLoading = NO; if ([Config Instance].isNetworkRunning) { [Tool ToastNotification:@"錯(cuò)誤 網(wǎng)絡(luò)無(wú)連接" andView:self.view andLoading:NO andIsBottom:NO]; } }]; isLoading = YES; [self.tableFriends reloadData]; }這個(gè)方法和getPath:parameters:success:failure:不同的在于請(qǐng)求方式是POST請(qǐng)求,可以向服務(wù)器里提交數(shù)據(jù);
轉(zhuǎn)載于:https://blog.51cto.com/duxinfeng/1208682
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的开源中国iOS客户端学习——(八)网络通信AFNetworking类库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python2.7 与 go1.2简单性
- 下一篇: Apache基础安装(一)