AFNetworking 详解

2024-05-08 13:38
文章标签 详解 afnetworking

本文主要是介绍AFNetworking 详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

// http://blog.csdn.net/duxinfeng2010/article/details/8620901?reload


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请求,可以向服务器里提交数据;

这篇关于AFNetworking 详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/970468

相关文章

Qt spdlog日志模块的使用详解

《Qtspdlog日志模块的使用详解》在Qt应用程序开发中,良好的日志系统至关重要,本文将介绍如何使用spdlog1.5.0创建满足以下要求的日志系统,感兴趣的朋友一起看看吧... 目录版本摘要例子logmanager.cpp文件main.cpp文件版本spdlog版本:1.5.0采用1.5.0版本主要

Linux ls命令操作详解

《Linuxls命令操作详解》通过ls命令,我们可以查看指定目录下的文件和子目录,并结合不同的选项获取详细的文件信息,如权限、大小、修改时间等,:本文主要介绍Linuxls命令详解,需要的朋友可... 目录1. 命令简介2. 命令的基本语法和用法2.1 语法格式2.2 使用示例2.2.1 列出当前目录下的文

MySQL中的交叉连接、自然连接和内连接查询详解

《MySQL中的交叉连接、自然连接和内连接查询详解》:本文主要介绍MySQL中的交叉连接、自然连接和内连接查询,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、引入二、交php叉连接(cross join)三、自然连接(naturalandroid join)四

Go 语言中的select语句详解及工作原理

《Go语言中的select语句详解及工作原理》在Go语言中,select语句是用于处理多个通道(channel)操作的一种控制结构,它类似于switch语句,本文给大家介绍Go语言中的select语... 目录Go 语言中的 select 是做什么的基本功能语法工作原理示例示例 1:监听多个通道示例 2:带

mysql的基础语句和外键查询及其语句详解(推荐)

《mysql的基础语句和外键查询及其语句详解(推荐)》:本文主要介绍mysql的基础语句和外键查询及其语句详解(推荐),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录一、mysql 基础语句1. 数据库操作 创建数据库2. 表操作 创建表3. CRUD 操作二、外键

Spring Boot项目部署命令java -jar的各种参数及作用详解

《SpringBoot项目部署命令java-jar的各种参数及作用详解》:本文主要介绍SpringBoot项目部署命令java-jar的各种参数及作用的相关资料,包括设置内存大小、垃圾回收... 目录前言一、基础命令结构二、常见的 Java 命令参数1. 设置内存大小2. 配置垃圾回收器3. 配置线程栈大小

鸿蒙中@State的原理使用详解(HarmonyOS 5)

《鸿蒙中@State的原理使用详解(HarmonyOS5)》@State是HarmonyOSArkTS框架中用于管理组件状态的核心装饰器,其核心作用是实现数据驱动UI的响应式编程模式,本文给大家介绍... 目录一、@State在鸿蒙中是做什么的?二、@Spythontate的基本原理1. 依赖关系的收集2.

Redis实现延迟任务的三种方法详解

《Redis实现延迟任务的三种方法详解》延迟任务(DelayedTask)是指在未来的某个时间点,执行相应的任务,本文为大家整理了三种常见的实现方法,感兴趣的小伙伴可以参考一下... 目录1.前言2.Redis如何实现延迟任务3.代码实现3.1. 过期键通知事件实现3.2. 使用ZSet实现延迟任务3.3

C语言函数递归实际应用举例详解

《C语言函数递归实际应用举例详解》程序调用自身的编程技巧称为递归,递归做为一种算法在程序设计语言中广泛应用,:本文主要介绍C语言函数递归实际应用举例的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录前言一、递归的概念与思想二、递归的限制条件 三、递归的实际应用举例(一)求 n 的阶乘(二)顺序打印

Python Faker库基本用法详解

《PythonFaker库基本用法详解》Faker是一个非常强大的库,适用于生成各种类型的伪随机数据,可以帮助开发者在测试、数据生成、或其他需要随机数据的场景中提高效率,本文给大家介绍PythonF... 目录安装基本用法主要功能示例代码语言和地区生成多条假数据自定义字段小结Faker 是一个 python