iOS 使用AFNetworking

简介: <div style="font-family:simsun; font-size:14px; line-height:21px; color:rgb(85,85,85)"> <span style="color:#ED1C24; word-wrap:normal; word-break:normal">一 下载:</span> <wbr>网址 -- <wbr><wbr><a targe
一 下载: 网址 --  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 使用
            #import "AFHTTPSessionManager.h"         AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; [manager GET:@"http://ods5pg0qp.
856 0
|
XML JSON 缓存
iOS - AFNetworking 网络请求
前言 在 iOS 开发中,一般情况下,简单的向某个 Web 站点简单的页面提交请求并获取服务器的响应,用 Xcode 自带的 NSURLConnection 是能胜任的。但是,在绝大部分下我们所需要访问的 Web 页面则是属于那种受到权限保护的页面,并不是有一个简单的 URL 可以访问的。
2165 0
|
XML JSON 数据格式
|
JavaScript iOS开发 数据格式
iOS开发之AFNetWorking初次使用会报错的坑
第一次用 CocoPods 安装好了 AFNetWorking 后,无论使用 Get 还是 Post,总是直接进入 failure 的 block,错误信息如下: error=Error Domain=com.
949 0
|
安全 iOS开发
iOS 9 平台上 AFNetworking 框架 3.0 版本解决的问题和问题解决
iOS 9 平台上 AFNetworking 框架 3.0 版本解决的问题和问题解决 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循“署名-非商业用途-保持一致”创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS、Android、Html5、Arduino、pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作。
1207 0
|
缓存 iOS开发 Go
|
开发者 iOS开发
iOS开发 - 用AFNetworking实现https单向验证,双向验证
iOS开发 - 用AFNetworking实现https单向验证,双向验证
345 0
iOS开发 - 用AFNetworking实现https单向验证,双向验证
|
移动开发 iOS开发
iOS开发:日志记录及AFNetworking请求
本篇文章主要目的是为了将用户操作习惯记录到本地文件,然后定期或者根据实际需要打包压缩上传到服务器,用以处理用户在闪退的时候,或需要详细了解具体某个用户在这一段时间的操作习惯。由于要压缩上传本地日志,顺道集成了AFNetWorking了post和get的接口请求,以及请求是接口失败后,错误信息显示,这个在开发的时候特别方便,后台可以在根据这些错误日志查询对应的问题。
284 0