开源中国iOS客户端学习——(八)网络通信AFNetworking类库

来源:互联网 发布:中国国籍 知乎 编辑:程序博客网 时间:2024/04/29 22:09

AFNetworking是一个轻量级的iOS网络通信类库,继ASI类库不在更新之后开发者们有一套不错选择;

AFNetworking类库源码下载和使用教程: https://github.com/AFNetworking/AFNetworking

如果想深入研究有官方文档介绍:http://afnetworking.github.com/AFNetworking/


在开源中国iOS客户端中关于AFNetworking类库的使用只用到了两个实例方法

(1)getPath:parameters:success:failure:

(2)postPath:parameters:success:failure:

他们用法基本相同,只是请求数据方式不同,一种是Get请求和Post请求Get是向服务器发索取数据的一种请求,也就相当于查询信息功能,不会修改类容,Post是向服务器提交数据的一种请求,影响数据内容;两种方法定义:


[cpp] view plaincopy
  1. - (void)getPath:(NSString *)path   
  2.      parameters:(NSDictionary *)parameters   
  3.         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success  
  4.         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure  
  5. {  
  6.     NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];  
  7.     AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];  
  8.     [self enqueueHTTPRequestOperation:operation];  
  9. }  

[cpp] view plaincopy
  1. - (void)postPath:(NSString *)path   
  2.       parameters:(NSDictionary *)parameters   
  3.          success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success  
  4.          failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure  
  5. {  
  6.     NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters];  
  7.     AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];  
  8.     [self enqueueHTTPRequestOperation:operation];  
  9. }  



getPath:parameters:success:failure:方法在程序中使用举例:

NewsView.m

[cpp] view plaincopy
  1. - (void)reload:(BOOL)noRefresh  
  2. {  
  3.     //如果有网络连接  
  4.     if ([Config Instance].isNetworkRunning) {  
  5.         if (isLoading || isLoadOver) {  
  6.             return;  
  7.         }  
  8.         if (!noRefresh) {  
  9.             allCount = 0;  
  10.         }  
  11.         int pageIndex = allCount/20;  
  12.         NSString *url;  
  13.   
  14.         switch (self.catalog) {  
  15.             case 1:  
  16.                 url = [NSString stringWithFormat:@"%@?catalog=%d&pageIndex=%d&pageSize=%d", api_news_list, 1, pageIndex, 20];  
  17.                 break;  
  18.             case 2:  
  19.                 url = [NSString stringWithFormat:@"%@?type=latest&pageIndex=%d&pageSize=%d", api_blog_list, pageIndex, 20];  
  20.                 break;  
  21.             case 3:  
  22.                 url = [NSString stringWithFormat:@"%@?type=recommend&pageIndex=%d&pageSize=%d", api_blog_list, pageIndex, 20];  
  23.                 break;  
  24.         }  
  25.   
  26.         [[AFOSCClient sharedClient]getPath:url parameters:Nil   
  27.               
  28.           success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  29.                  
  30.             [Tool getOSCNotice2:operation.responseString];  
  31.             isLoading = NO;  
  32.             if (!noRefresh) {  
  33.                 [self clear];  
  34.             }  
  35.   
  36.             @try {  
  37.                 NSMutableArray *newNews = self.catalog <= 1 ?  
  38.                   
  39.                 [Tool readStrNewsArray:operation.responseString andOld: news]:  
  40.                 [Tool readStrUserBlogsArray:operation.responseString andOld: news];  
  41.                 int count = [Tool isListOver2:operation.responseString];  
  42.                 allCount += count;  
  43.                 if (count < 20)  
  44.                 {  
  45.                     isLoadOver = YES;  
  46.                 }  
  47.                 [news addObjectsFromArray:newNews];  
  48.                 [self.tableNews reloadData];  
  49.                 [self doneLoadingTableViewData];  
  50.                   
  51.                 //如果是第一页 则缓存下来  
  52.                 if (news.count <= 20) {  
  53.                     [Tool saveCache:5 andID:self.catalog andString:operation.responseString];  
  54.                 }  
  55.             }  
  56.             @catch (NSException *exception) {  
  57.                 [NdUncaughtExceptionHandler TakeException:exception];  
  58.             }  
  59.             @finally {  
  60.                 [self doneLoadingTableViewData];  
  61.             }  
  62.         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  63.             NSLog(@"新闻列表获取出错");  
  64.             //如果是刷新  
  65.             [self doneLoadingTableViewData];  
  66.               
  67.             if ([Config Instance].isNetworkRunning == NO) {  
  68.                 return;  
  69.             }  
  70.             isLoading = NO;  
  71.             if ([Config Instance].isNetworkRunning) {  
  72.                 [Tool ToastNotification:@"错误 网络无连接" andView:self.view andLoading:NO andIsBottom:NO];  
  73.             }  
  74.         }];  
  75.         isLoading = YES;  
  76.         [self.tableNews reloadData];  
  77.     }  
  78.     //如果没有网络连接  
  79.     else  
  80.     {  
  81.         NSString *value = [Tool getCache:5 andID:self.catalog];  
  82.         if (value) {  
  83.             NSMutableArray *newNews = [Tool readStrNewsArray:value andOld:news];  
  84.             [self.tableNews reloadData];  
  85.             isLoadOver = YES;  
  86.             [news addObjectsFromArray:newNews];  
  87.             [self.tableNews reloadData];  
  88.             [self doneLoadingTableViewData];  
  89.         }  
  90.     }  
  91. }  

分析一下这里面的代码:

首先是做一个网络连接判断,在开源中国iOS客户端学习——(六)网络连接检测一文中介绍了,作者并不是用这种方法来判断,而是使用getPath:parameters:success:failure:来判断网络的连接,方法使用AFHTTPRequestOperation和“PATCH”请求HTTP客户端操作队列,使用到了block块(iOS 4.0+特性),URL请求成功执行success块里操作,这里面block块没有返回值,接受两个参数,创建请求操作和响应数据请求,URL请求失败执行failure里面的方法,这个block块里仍没有返回值,接受两个参数创建请求操作和NSError对象,描述网络或解析错误状况;


 if()中的方法[Config Instance].isNetworkRunning==YES的,如果程序加载或者已经加载完毕什么也不返回,如果程序没有加载数据,将数据列表数量显示为0,接下来是在switch()中,根据使用者选择设置不同API接口(下图),然后就是解析显示数据信息,显示在视图中;

  

在AFNetwork 文件夹中,作者自己添加了一个AFOSCClient类,该类继承AFHTTPClient,又设计了一个sharedClient的类方法,从返回的结果可以推测出它是通过API请求返回json类型的数据,具体什么作用还没看出来;


[Tool getOSCNotice2:operation.responseString];是封装在在Tool类中的解析获取的XML的文件


URL请求成功,还做了一个程序异常处理,防止请求数据过成功程序异常崩溃

 关于@try @catch @finally异常处理的使用:


@try 

//执行的代码,其中可能有异常。一旦发现异常,则立即跳到catch执行。否则不会执行catch里面的内容 

@catch 

//除非try里面执行代码发生了异常,否则这里的代码不会执行 

@finally 

//不管什么情况都会执行,包括try catch 里面用了return ,可以理解为只要执行了try或者catch,就一定会执行 finally


如果URL请求的数据出错,则反应网络不连通,数据不能加载,则弹出GCDiscreetNotificationView提示视图  提示网络错误;


postPath:parameters:success:failure:方法在程序中使用举例:

FriendsView.m

[cpp] view plaincopy
  1. -(void)reload:(BOOL)noRefresh  
  2. {  
  3.     if (isLoadOver) {  
  4.         [self doneLoadingTableViewData];  
  5.         return;  
  6.     }  
  7.       
  8.     [[AFOSCClient sharedClient] postPath:api_friends_list   
  9.             parameters:[NSDictionary dictionaryWithObjectsAndKeys:segement.selectedSegmentIndex == 0 ? @"1" : @"0",@"relation",  
  10.                         [NSString stringWithFormat:@"%d", friends.count/20],@"pageIndex",  
  11.                         @"20",@"pageSize",  
  12.                         [NSString stringWithFormat:@"%d", [Config Instance].getUID],@"uid",nil] success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  13.                   
  14.                 if (!noRefresh) {  
  15.                     [self clear];  
  16.                 }  
  17.                   
  18.                 [self doneLoadingTableViewData];  
  19.                 isLoading = NO;  
  20.                 NSString *response = operation.responseString;  
  21.                 [Tool getOSCNotice2:response];  
  22.                 @try {  
  23.                       
  24.                     TBXML *xml = [[TBXML alloc] initWithXMLString:response error:nil];  
  25.                     TBXMLElement *root = xml.rootXMLElement;  
  26.                     //显示  
  27.                     TBXMLElement *_friends = [TBXML childElementNamed:@"friends" parentElement:root];  
  28.                     if (!_friends) {  
  29.                         isLoadOver = YES;  
  30.                         [self.tableFriends reloadData];  
  31.                         return;  
  32.                     }  
  33.                     TBXMLElement *first = [TBXML childElementNamed:@"friend" parentElement:_friends];  
  34.                     if (first == nil) {  
  35.                         [self.tableFriends reloadData];  
  36.                         isLoadOver = YES;  
  37.                         return;  
  38.                     }  
  39.                     NSMutableArray *newFriends = [[NSMutableArray alloc] initWithCapacity:20];  
  40.                     TBXMLElement *name = [TBXML childElementNamed:@"name" parentElement:first];  
  41.                     TBXMLElement *userid = [TBXML childElementNamed:@"userid" parentElement:first];  
  42.                     TBXMLElement *portrait = [TBXML childElementNamed:@"portrait" parentElement:first];  
  43.                     TBXMLElement *expertise = [TBXML childElementNamed:@"expertise" parentElement:first];  
  44.                     TBXMLElement *gender = [TBXML childElementNamed:@"gender" parentElement:first];  
  45.                     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];  
  46.                     if (![Tool isRepeatFriend: friends andFriend:f]) {  
  47.                         [newFriends addObject:f];  
  48.                     }  
  49.                     while (first) {  
  50.                         first = [TBXML nextSiblingNamed:@"friend" searchFromElement:first];  
  51.                         if (first) {  
  52.                             name = [TBXML childElementNamed:@"name" parentElement:first];  
  53.                             userid = [TBXML childElementNamed:@"userid" parentElement:first];  
  54.                             portrait = [TBXML childElementNamed:@"portrait" parentElement:first];  
  55.                             expertise = [TBXML childElementNamed:@"expertise" parentElement:first];  
  56.                             gender = [TBXML childElementNamed:@"gender" parentElement:first];  
  57.                             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];  
  58.                             if (![Tool isRepeatFriend:friends andFriend:f]) {  
  59.                                 [newFriends addObject:f];  
  60.                             }  
  61.                         }  
  62.                         else  
  63.                             break;  
  64.                     }  
  65.                     if (newFriends.count < 20) {  
  66.                         isLoadOver = YES;  
  67.                     }  
  68.                       
  69.                     [friends addObjectsFromArray:newFriends];  
  70.                     [self.tableFriends reloadData];  
  71.                       
  72.                 }  
  73.                 @catch (NSException *exception) {  
  74.                     [NdUncaughtExceptionHandler TakeException:exception];  
  75.                 }  
  76.                 @finally {  
  77.                     [self doneLoadingTableViewData];  
  78.                 }  
  79.                   
  80.             } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  81.                  
  82.                 NSLog(@"好友列表获取出错");  
  83.                   
  84.                 [self doneLoadingTableViewData];  
  85.                 isLoading = NO;  
  86.                 if ([Config Instance].isNetworkRunning) {  
  87.                     [Tool ToastNotification:@"错误 网络无连接" andView:self.view andLoading:NO andIsBottom:NO];  
  88.                 }  
  89.                   
  90.             }];  
  91.       
  92.     isLoading = YES;  
  93.     [self.tableFriends reloadData];  
  94. }  

这个方法和getPath:parameters:success:failure:不同的在于请求方式是POST请求,可以向服务器里提交数据;

0 0
原创粉丝点击