简单的AFNetWorking用法:加载网络图片和请求JSON数据

来源:互联网 发布:vb库存管理系统源码 编辑:程序博客网 时间:2024/04/28 21:23

简单的AFNetWorking用法:加载网络图片和请求JSON数据

 

使用AFNetWorking:

1、首先将AFNetWorking文件夹导入项目

2、添加类库Security.framework、MobileCoreServices.framework、SystemConfiguration.framework

3、在使用的地方#import”AFNetworking.h”

 

1、异步加载图片:通过队列实现,支持缓存,当下次下载相同的图片时,系统会自动调用缓存,而不再请求网络

AFN中提供了加载网络图片的方法

以下是一个小Demo,简单的说明该方法的用法

    placeholderImage:一个图片占位符,显示最初的图像设置,直到网络图片加载完成才会被网络图片替代,否则一直是设置好的这张图片。

    success:NSURLRequest *request客户端的请求、 NSHTTPURLResponse *response从服务器接收到的响应、UIImage *image从服务器请求来的图片

        NSURL *url = [NSURL URLWithString:@"http://pic1.win4000.com/pic/4/3f/4124407336.jpg"];    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];    [_imageView setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:@"image"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {        _imageView.image = image;        [_imageView setNeedsDisplay];    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {        NSLog(@"图片加载失败:%@",error);    }];        [self.view addSubview:_imageView];

2、AFN请求JSON数据

先构建一个url,然后构建网络请求request,

创建AFJSONRequestOperation来请求json数据,请求成功则运行success的block语句,可以在语句中将json数据转化成字典存储起来,以便使用,如果失败则会运行failure语句,可以把失败的原因打印出来方便更正。注意,创建的AFJSONRequestOperation操作一定要有启动的方法: [operation start];否则程序不会发起请求

    //构建url    NSString *urlString = [NSString stringWithFormat:@"http://www.weather.com.cn/data/sk/%@.html",_dic.allValues[row]];    NSURL *url = [NSURL URLWithString:urlString];    //构建网络请求    NSURLRequest *request = [NSURLRequest requestWithURL:url];    //添加字符集    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObjects:@"application/json",@"text/html", nil]];    //创建请求json数据的操作    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {        NSDictionary *result = (NSDictionary *)JSON;//        result = [result valueForKey:@"weatherinfo"];
//这里有个误区,在回调中,可以直接对UI进行操作,不需要在写回到主线程的GCD语句,不过写上也不会出错//        dispatch_async(dispatch_get_main_queue(), ^{//            _cityLabel.text = [result objectForKey:@"city"];//            _tempLabel.text = result[@"temp"];//            _wdLabel.text = result[@"WD"];//            _wlLabel.text = result[@"WS"];//            _sdlabel.text = result[@"SD"];//            _timeLabel.text = result[@"time"];//        });    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {        NSLog(@"加载数据失败:%@",error);    }];    [operation start];

被注释的代码为我的Demo中的对json数据的使用,可以忽略。


如果出现Error Domain=AFNetworkingErrorDomain Code=-1016的错误,如下

:Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {(    "text/json",    "application/json",    "text/javascript")}, got text/html" UserInfo=0x7658b90 {NSLocalizedRecoverySuggestion={"weatherinfo":{"city":"房山","cityid":"101011200","temp":"21","WD":"南风","WS":"2级","SD":"56%","WSE":"2","time":"17:05","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1016"}}, AFNetworkingOperationFailingURLRequestErrorKey=<NSURLRequest http://www.weather.com.cn/data/sk/101011200.html>, NSErrorFailingURLKey=http://www.weather.com.cn/data/sk/101011200.html, NSLocalizedDescription=Expected content type {(    "text/json",    "application/json",    "text/javascript")}, got text/html, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x773e650>}

原因是缺少它需要的字符集,只需要在请求数据语句之前加如下一句,即可

    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObjects:@"application/json",@"text/html", nil]];

AFHTTPRequestOperationManager:

该类封装通过HTTP与Web应用程序进行通信的方法,包括要求制作,响应序列化,网络可达性监控和安全性,以及安全经营管理的常见模式。

1、GET请求:

  //1、管理器    AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];//设置返回格式//开始没写这句  出现了诡异的错误    manager.responseSerializer = [AFHTTPResponseSerializer serializer];    //2、设置登录参数    NSDictionary *dic =@{@"username":@"wang",@"passwork":@"920911"};    //3、    [managerGET:@"http://www.baidu.com" parameters:dicsuccess:^(AFHTTPRequestOperation *operation, id responseObject) {        NSLog(@"GET----------%@,%@",responseObject,[NSThreadcurrentThread]);    } failure:^(AFHTTPRequestOperation*operation, NSError *error) {        NSLog(@"failure:%@",error);    }];

 

2、POST请求:(带有表单参数的POST请求)

AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];    manager.responseSerializer =[AFHTTPResponseSerializer serializer];    NSDictionary *dic =@{@"name":@"hong"};    [managerPOST:@"http://www.baidu.com" parameters:dicsuccess:^(AFHTTPRequestOperation *operation, id responseObject) {       NSLog(@"JSON:%@",responseObject);    } failure:^(AFHTTPRequestOperation*operation, NSError *error) {        NSLog(@"failure:%@",error);    }];

   3、POSTMulti-Part格式的表单文件上传请求

    AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];    manager.responseSerializer =[AFHTTPResponseSerializer serializer];    NSDictionary *dic =@{@"name":@"hong"};    NSURL *url = [NSURL fileURLWithPath:@"本地表单地址"];    [manager POST:@"请求的网址"parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>formData) {        [formData appendPartWithFileURL:urlname:@"表单的名字" error:nil];    } success:^(AFHTTPRequestOperation*operation, id responseObject) {       NSLog(@"success--------%@",responseObject);    } failure:^(AFHTTPRequestOperation*operation, NSError *error) {       NSLog(@"failure--------%@",error);    }];

4、可能会遇到的bug们

研究AFNetworking中遇到的那些bug君们

向服务器请求一个信息 

  //1、管理器    AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];//设置返回格式//开始没写这句  出现了诡异的错误 //   manager.responseSerializer = [AFHTTPResponseSerializer serializer];    //2、设置登录参数    NSDictionary *dic =@{@"username":@"wang",@"passwork":@"920911"};    //3、    [managerGET:@"http://www.baidu.com" parameters:dicsuccess:^(AFHTTPRequestOperation *operation, id responseObject) {        NSLog(@"GET----------%@,%@",responseObject,[NSThreadcurrentThread]);    } failure:^(AFHTTPRequestOperation*operation, NSError *error) {        NSLog(@"failure:%@",error);    }];

错误:

failure:ErrorDomain=com.alamofire.error.serialization.response Code=-1016 "Requestfailed: unacceptable content-type: text/html" UserInfo=0x8bc2a00{com.alamofire.serialization.response.error.response=<NSHTTPURLResponse:0x8bbf900>

解决办法:

添加一句:    manager.responseSerializer =[AFHTTPResponseSerializer serializer];


 


0 0
原创粉丝点击