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

相关文章

pycharm远程连接服务器运行pytorch的过程详解

《pycharm远程连接服务器运行pytorch的过程详解》:本文主要介绍在Linux环境下使用Anaconda管理不同版本的Python环境,并通过PyCharm远程连接服务器来运行PyTorc... 目录linux部署pytorch背景介绍Anaconda安装Linux安装pytorch虚拟环境安装cu

一文详解如何在Python中使用Requests库

《一文详解如何在Python中使用Requests库》:本文主要介绍如何在Python中使用Requests库的相关资料,Requests库是Python中常用的第三方库,用于简化HTTP请求的发... 目录前言1. 安装Requests库2. 发起GET请求3. 发送带有查询参数的GET请求4. 发起PO

Python进行PDF文件拆分的示例详解

《Python进行PDF文件拆分的示例详解》在日常生活中,我们常常会遇到大型的PDF文件,难以发送,将PDF拆分成多个小文件是一个实用的解决方案,下面我们就来看看如何使用Python实现PDF文件拆分... 目录使用工具将PDF按页数拆分将PDF的每一页拆分为单独的文件将PDF按指定页数拆分根据页码范围拆分

Java中的Cursor使用详解

《Java中的Cursor使用详解》本文介绍了Java中的Cursor接口及其在大数据集处理中的优势,包括逐行读取、分页处理、流控制、动态改变查询、并发控制和减少网络流量等,感兴趣的朋友一起看看吧... 最近看代码,有一段代码涉及到Cursor,感觉写法挺有意思的。注意是Cursor,而不是Consumer

SpringBoot项目注入 traceId 追踪整个请求的日志链路(过程详解)

《SpringBoot项目注入traceId追踪整个请求的日志链路(过程详解)》本文介绍了如何在单体SpringBoot项目中通过手动实现过滤器或拦截器来注入traceId,以追踪整个请求的日志链... SpringBoot项目注入 traceId 来追踪整个请求的日志链路,有了 traceId, 我们在排

HTML5中下拉框<select>标签的属性和样式详解

《HTML5中下拉框<select>标签的属性和样式详解》在HTML5中,下拉框(select标签)作为表单的重要组成部分,为用户提供了一个从预定义选项中选择值的方式,本文将深入探讨select标签的... 在html5中,下拉框(<select>标签)作为表单的重要组成部分,为用户提供了一个从预定义选项中

Python中多线程和多进程的基本用法详解

《Python中多线程和多进程的基本用法详解》这篇文章介绍了Python中多线程和多进程的相关知识,包括并发编程的优势,多线程和多进程的概念、适用场景、示例代码,线程池和进程池的使用,以及如何选择合适... 目录引言一、并发编程的主要优势二、python的多线程(Threading)1. 什么是多线程?2.

Java 8 Stream filter流式过滤器详解

《Java8Streamfilter流式过滤器详解》本文介绍了Java8的StreamAPI中的filter方法,展示了如何使用lambda表达式根据条件过滤流式数据,通过实际代码示例,展示了f... 目录引言 一.Java 8 Stream 的过滤器(filter)二.Java 8 的 filter、fi

Rust中的BoxT之堆上的数据与递归类型详解

《Rust中的BoxT之堆上的数据与递归类型详解》本文介绍了Rust中的BoxT类型,包括其在堆与栈之间的内存分配,性能优势,以及如何利用BoxT来实现递归类型和处理大小未知类型,通过BoxT,Rus... 目录1. Box<T> 的基础知识1.1 堆与栈的分工1.2 性能优势2.1 递归类型的问题2.2

springboot的调度服务与异步服务使用详解

《springboot的调度服务与异步服务使用详解》本文主要介绍了Java的ScheduledExecutorService接口和SpringBoot中如何使用调度线程池,包括核心参数、创建方式、自定... 目录1.调度服务1.1.JDK之ScheduledExecutorService1.2.spring