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

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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
开源电子签章客户端 c 是一款基于开源技术开发的电子签章客户端软件。这款软件通过使用c语言进行编码,具有跨平台、高效稳定的特点。 首先,开源电子签章客户端 c 的跨平台特性使得它能够在多个操作系统上运行,无论是Windows、Linux还是MacOS,用户都可以方便地使用这款软件进行电子签章操作。这样一来,无论用户在哪个操作系统下工作,都能够享受到开源电子签章客户端 c 提供的便利。 其次,开源电子签章客户端 c 的高效稳定性使得用户能够快速、稳定地完成签章操作。使用c语言进行编码,它能够充分利用计算机的资源,提高程序的运行效率,使得签章过程更加快速和流畅。同时,开源电子签章客户端 c 经过长时间的开发和测试,确保了软件的稳定性和可靠性,用户可以放心地使用该软件进行电子签章。 此外,开源电子签章客户端 c 还提供了丰富的功能和灵活的配置选项,以满足不同用户的需求。用户可以根据自己的实际情况,自定义签章的样式、位置和大小等参数,使得签章结果更加符合个人需求和业务要求。同时,该客户端还支持多种签章文件格式,如PDF、Word、Excel等,用户可以根据需要选择合适的文件格式进行签章操作。 总之,开源电子签章客户端 c 是一款功能强大、稳定高效的电子签章软件,它具备跨平台的特性、高效稳定的运行以及丰富灵活的配置选项。无论用户是个人还是企业,都可以通过使用开源电子签章客户端 c 来简化和提高签章工作的效率,实现数字化办公的目标。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值