iOS 使用AFNetworking

简介: <p style="padding-top:0px; padding-bottom:0px; margin-top:0px; margin-bottom:0px; clear:both; height:auto; overflow:hidden; color:rgb(80,80,80); font-family:宋体,'Arial Narrow',arial,serif; font-siz

一 下载: 网址 -- github

二 环境:

  需要引入的库 - CoreLocation.framework

  SystemConfiguration.framework

  MobileCoreServices.framework

  Security.framework

  需要在 ARC 的环境下 - 非 ARC 的工程中 - 请添加 -fobjc-arc 

三 结构:

1 : AFHTTPClient  --   提供了一个方便的网络交互接口,包括默认头,身份验证,是否连接到网络,批量处理操作,查询字符串参数序列化,已经多种表单请求

2 : AFHTTPRequestOperation -- 

和它得子类可以基于http状态和内容列下来区分是否成功请求了

3 : AFURLConnectionOperation -- 

和它的子类继承NSOperation的,允许请求被取消,暂停/恢复和由NSOperationQueue进行管理。

4 : AFURLConnectionOperation -- 

可以让你轻松得完成上传和下载,处理验证,监控上传和下载进度,控制的缓存。

四 使用 :

用法场景 1 : 请求api数据

方法1 --

创建一个 AFHTTPClient 实例

AFHTTPClient * client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://api.jiepang.com"]];

// 这里一定要有一个 baseURL - 不然会抛出一个异常 -- 

创建一个 NSURLRequest 实例

NSDictionary * params = @{@"apiver": @"4",@"id" : @"830755858",@"extra_info": @"1"};

    NSURLRequest * request = [client requestWithMethod:@"POST"

                                              path:@"users/show"

                                        parameters:params];

    @param  method 网络请求方式,比如 GET,POST,PUT,DELETE , 不能为 nil -- 

    @param  path   和 baseURL 组合成为一个 url  -- 通俗的说,就是我们调用的接口 -- 比如,我想调用http://api.jiepang.com/users/show,这个接口 -- 那么 baseURL 为 http://api.jiepang.com -- path 为users/show 

    @param  parameters 网络请求参数 -- http://api.jiepang.com/v1/users/show?id=123 -- id=123 就是这个参数

创建一个 AFHTTPRequestOperation 实例进行网络链接

AFHTTPRequestOperation * operation = [client HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {

        

        NSLog(@"success obj == %@",responseObject);

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        

        NSLog(@"faild , error == %@ ", error);

    }];

    [operation start];

    这样 - 一次简单的调用就OK了 - 

    当然也可以,用封装好的其它方法 -- 

    - (void)getPath:(NSString *)path

     parameters:(NSDictionary *)parameters

        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

    - (void)postPath:(NSString *)path

      parameters:(NSDictionary *)parameters

         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

    - (void)putPath:(NSString *)path

     parameters:(NSDictionary *)parameters

        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

    - (void)deletePath:(NSString *)path

        parameters:(NSDictionary *)parameters

           success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

           failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

- (void)patchPath:(NSString *)path

parameters:(NSDictionary *)parameters

 success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

 failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

省去了组装 Resquest 的时间  --

比如 - 

方法二 --

    [client getPath:path

     parameters:params

        success:^(AFHTTPRequestOperation *operation, id responseObject) {

                   NSString * obj = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

                   NSLog(@"obj == %@",obj);

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            NSLog(@"faild -- ");

        }];

    这和上面的效果是一样的 -- 

    我们看到,前面返回的数据全部为 NSdata - 为我们添加了麻烦 -- 而且我们大部分的 api 返回数据都为 json -- 

    同样 - 我们可以用 AFHTTPRequestOperation 的子类 AFJSONRequestOperation 来替代 -- 

    方法三 -- 

       NSDictionary * params = @{@"apiver": @"4",@"id" : @"830755858",@"extra_info": @"1"};

    

    

AFHTTPClient * client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://api.jiepang.com"]];

    

    NSURLRequest * request = [client requestWithMethod:@"POST"

                                                  path:@"users/show"

                                            parameters:params];

    

    

    AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        

        NSLog(@"json == %@",JSON);

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

        

        NSLog(@"faild -- ");

    }];

    

    [operation start];

    使用场景 2 : 异步加载图片 

    AFImageRequestOperation 是继承自 AFHTTPRequestOperation -- 所以 - 方法大同小异 -- 

    NSString * url = @"http://c.hiphotos.baidu.com/album/w=2048/sign=1d7ca85bac345982c58ae29238cc30ad/f2deb48f8c5494ee7abe33362cf5e0fe99257e04.jpg";

    // 这是一个大美女

    

    创建 request

    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]

                                              cachePolicy:NSURLRequestReloadIgnoringLocalCacheData

                                          timeoutInterval:30];

    

    AFImageRequestOperation * operation = [AFImageRequestOperation imageRequestOperationWithRequest:request

                                                                               imageProcessingBlock:^UIImage *(UIImage *image) {

                                                                                   

                                                                                   UIImage * tempImage = [UIImage imageWithCGImage:

                                                                                                         CGImageCreateWithImageInRect(image.CGImage,ake(0, 0, image.size.width, image.size.height/2.0))];

                                                                                   

                                                                                   return tempImage;

                                                                                   

                                                                               } success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

                                                                                   

                                                                                   NSLog(@"reload image success ");

                                                                                   

                                                                                   _imageView.image = image;

                                                                               } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {

                                                                                   

                                                                                   NSLog(@"reload image faild , error == %@ ",error);

                                                                                   

                                                                               }];

    

    [operation start];

    这个方法里有三个block ,success 和 failure 不说 -- processimageBlock -- 是在 图片加载完后,对 图片 处理的 block ,可以为 nil ,在 success 之前调用  --

目录
相关文章
|
移动开发 iOS开发
iOS开发:日志记录及AFNetworking请求
本篇文章主要目的是为了将用户操作习惯记录到本地文件,然后定期或者根据实际需要打包压缩上传到服务器,用以处理用户在闪退的时候,或需要详细了解具体某个用户在这一段时间的操作习惯。由于要压缩上传本地日志,顺道集成了AFNetWorking了post和get的接口请求,以及请求是接口失败后,错误信息显示,这个在开发的时候特别方便,后台可以在根据这些错误日志查询对应的问题。
284 0
|
XML JSON 数据格式
|
JavaScript iOS开发 数据格式
iOS开发之AFNetWorking初次使用会报错的坑
第一次用 CocoPods 安装好了 AFNetWorking 后,无论使用 Get 还是 Post,总是直接进入 failure 的 block,错误信息如下: error=Error Domain=com.
946 0
|
XML JSON 数据格式
iOS开发网络数据之AFNetworking使用
<p class="p1" style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"> 如何选择AFNetworking版本</p> <p class="p2" style="color:rgb(51,51,51); font-family:Arial; font-size:14px
1500 0
|
1月前
|
API 数据安全/隐私保护 iOS开发
利用uni-app 开发的iOS app 发布到App Store全流程
利用uni-app 开发的iOS app 发布到App Store全流程
84 3
|
3月前
|
存储 iOS开发
iOS 开发,如何进行应用的本地化(Localization)?
iOS 开发,如何进行应用的本地化(Localization)?
122 2
|
3月前
|
存储 数据建模 数据库
IOS开发数据存储:什么是 UserDefaults?有哪些替代方案?
IOS开发数据存储:什么是 UserDefaults?有哪些替代方案?
39 0
|
3月前
|
安全 编译器 Swift
IOS开发基础知识: 对比 Swift 和 Objective-C 的优缺点。
IOS开发基础知识: 对比 Swift 和 Objective-C 的优缺点。
91 2
|
3月前
|
API 开发工具 iOS开发
iOS 开发高效率工具包:10 大必备工具
iOS 开发高效率工具包:10 大必备工具
47 1
|
6天前
|
API 定位技术 iOS开发
IOS开发基础知识:什么是 Cocoa Touch?它在 iOS 开发中的作用是什么?
【4月更文挑战第18天】**Cocoa Touch** 是iOS和Mac OS X应用的核心框架,包含面向对象库、运行时系统和触摸优化工具。它提供Mac验证的开发模式,强调触控接口和性能,涵盖3D图形、音频、网络及设备访问API,如相机和GPS。是构建高效iOS应用的基础,对开发者至关重要。
9 0