AFN的使用
首先得下载AFNetworking库文件,下载时得首先弄清楚,你将要开发的软件兼容的最低版本是多少。AFNetworking 2.0或者之后的版本需要xcode5.0版本并且只能为IOS6或更高的手机系统上运行,如果开发MAC程序,那么2.0版本只能在MAC OS X 10.8或者更高的版本上运行。
NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 从URL获取json数据
AFJSONRequestOperation *operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON) {
NSLog(@"获取到的数据为:%@",JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) {
NSLog(@"发生错误!%@",error);
}];
[operation1 start];
第二种方法,利用AFHTTPRequestOperation 先获取到字符串形式的数据,然后转换成json格式,将NSString格式的数据转换成json数据,利用IOS5自带的json解析方法:
NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *html = operation.responseString;
NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
id dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"获取到的数据为:%@",dict);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"发生错误!%@",error);
}];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];
如果发生Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x14defc80 {NSUnderlyingError=0x14deea10 "bad URL", NSLocalizedDescription=bad URL这个错误,请检查URL编码格式。有没有进行stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
如何通过URL获取图片
异步获取图片,通过队列实现,而且图片会有缓存,在下次请求相同的链接时,系统会自动调用缓存,而不从网上请求数据。
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 100.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
[self.view addSubview:imageView];
上面的方法是官方提供的,还有一种方法,
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.scott-sherwood.com/wp-content/uploads/2013/01/scene.png"]];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
self.backgroundImageView.image = image;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Error %@",error);
}];
[operation start];
如果使用第一种URLWithString: placeholderImage:会有更多的细节处理,其实实现还是通过AFImageRequestOperation处理,可以点击URLWithString: placeholderImage:方法进去看一下就一目了然了。所以我觉得还是用第一种好。
如何通过URL获取plist文件
通过url获取plist文件的内容,用的很少,这个方法在官方提供的方法里面没有
NSString *weatherUrl = @"http://www.calinks.com.cn/buick/kls/Buickhousekeeper.plist";
NSURL *url = [NSURL URLWithString:[weatherUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[AFPropertyListRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
AFPropertyListRequestOperation *operation = [AFPropertyListRequestOperation propertyListRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) {
NSLog(@"%@",(NSDictionary *)propertyList);
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) {
NSLog(@"%@",error);
}];
[operation start];
如果稍不留神,可能就出现Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {(
"application/x-plist"
)}, got text/plain" UserInfo=0x16e91ce0 {NSLocalizedRecoverySuggestion=
...
...
, AFNetworkingOperationFailingURLRequestErrorKey= { }, NSErrorFailingURLKey=, NSLocalizedDescription=Expected content type {(
"application/x-plist"
)}, got text/plain, AFNetworkingOperationFailinponseErrorKey= { URL: } { status code: 200, headers {
"Accept-Ranges" = bytes;
Connection = "keep-alive";
"Content-Length" = 974;
"Content-Type" = "text/plain";
Date = "Sat, 25 Jan 2014 07:29:26 GMT";
Etag = ""1014c2-3ce-4ee63e1c80e00"";
"Last-Modified" = "Wed, 25 Dec 2013 23:04:24 GMT";
Server = "nginx/1.4.2";
} }}
可能还会出现乱码,解决办法就是[AFPropertyListRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
如何通过URL获取XML数据
xml解析使用AFXMLRequestOperation,需要实现苹果自带的NSXMLParserDelegate委托方法,XML中有一些不需要的协议格式内容,所以就不能像json那样解析,还得实现委托。我之前有想过能否所有的XML链接用一个类处理,而且跟服务端做了沟通,结果很不方便,效果不好。XML大多标签不同,格式也不固定,所以就有问题,使用json就要方便的多。
第一步;在.h文件中加入委托NSXMLParserDelegate
第二步;在.m文件方法中加入代码
NSURL *url = [NSURL URLWithString:@"http://113.106.90.22:5244/sshopinfo"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFXMLRequestOperation *operation =
[AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser setShouldProcessNamespaces:YES];
[XMLParser parse];
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
NSLog(@"%@",error);
}];
[operation start];
第三步;在.m文件中实现委托方法
//在文档开始的时候触发
-(void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(@"解析开始!");
}
//解析起始标记
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
NSLog(@"标记:%@",elementName);
}
//解析文本节点
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSLog(@"值:%@",string);
}
//解析结束标记
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
NSLog(@"结束标记:%@",elementName);
}
//文档结束时触发
-(void) parserDidEndDocument:(NSXMLParser *)parser{
NSLog(@"解析结束!");
}
运行的结果:
如何使用AFHTTPClient进行web service操作
POST请求.做网页的朋友们这个方法用的比较多。在要经常调用某个请求时,可以封装,节省资源。
BaseURLString =
@"http://www.raywenderlich.com/downloads/weather_sample/";
NSURL
*baseURL = [NSURL
URLWithString:[NSString
stringWithFormat:BaseURLString]];
NSDictionary *parameters = [NSDictionary
dictionaryWithObject:@"json" forKey:@"format"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:@"Accept" value:@"text/html"];
[client postPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation,
id responseObject) {
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"POST请求:%@",newStr);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
}];
[client getPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation,
id responseObject) {
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"GET请求:%@",newStr);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
}];
运行结果:
YES;
Error: Error Domain=AFNetworkingErrorDomain Code=-1016
"Request failed: unacceptable content-type: text/html"
UserInfo=0x16774de0
{NSErrorFailingURLKey=http://192.168.2.2:8181/ecar/tsp/uploadLocation?CID=781666&serviceType=1,
AFNetworkingOperationFailinponseErrorKey= { URL:
http://192.168.2.2:8181/ecar/tsp/uploadLocation?CID=781666&serviceType=1
} { status code: 200, headers {
XXX
} }, NSLocalizedDescription=Request failed: unacceptable
content-type: text/html}
返回数据格式不对。注销这句话: op.responseSerializer
= [AFJSONResponseSerializer serializer];然后将返回的数据自己转换。
转载自: http://blog.sina.com.cn/s/blog_68661bd80101r1xz.html
AFN的使用的更多相关文章
- AFN解析器里的坑
AFN框架是用来用来发送网络请求的,它的好处是可以自动给你解析JSON数据,还可以发送带参数的请求AFN框架还可以监测当前的网络状态,还支持HTTPS请求,分别对用的类为AFNetworkReacha ...
- IOS开发之—— 在AFN基础上进行的网络请求的封装
网络请求的思路:如果请求成功的话AFN的responseObject就是解析好的. 1发送网络请求:get/post/或者别的 带上URL,需要传的参数 2判断后台网络状态码有没有请求成功: 3 请求 ...
- Swift -- 对AFN框架的封装
Swift -- 对AFN框架的封装 一.封装AFN的目的 简单的说: 解耦 日常工作中,我们一般都不会去直接使用AFNetWorking来直接发送网络请求,因为耦合性太强,假设有多个控制器都使用AF ...
- 通读AFN③--HTTPS访问控制(AFSecurityPolicy),Reachability(AFNetworkReachabilityManager)
这一篇主要介绍使用AFN如何访问HTTPS网站以及这些做法的实现原理,还有介绍AFN的网络状态监测部分AFNetworkReachabilityManager,这个模块会和苹果官方推荐的Reachab ...
- iOS项目相关@AFN&SDWeb的二次封装
一,AFNetworking跟SDWebImge是功能强大且常用的第三方,然而在实际应用中需要封装用来复用今天就跟大家分享一下AFN&SDWeb的二次封装 1. HttpClient.h及.m ...
- 通读AFN②--AFN的上传和下载功能分析、SessionTask及相应的session代理方法的使用细节
这一部分主要研究AFN的上传和下载功能,中间涉及到各种NSURLSessionTask的一些创建的解析和HTTPSessionManager对RESTful风格的web应用的支持,同时会穿插一点NSU ...
- 通读AFN①--从创建manager到数据解析完毕
流程梳理 今天开始会写几篇关于AFN源码解读的一些Blog,首先要梳理一下AFN的整体结构(主要是讨论2.x版本的Session访问模块): 我们先看看我们最常用的一段代码: AFHTTPSessio ...
- iOS. PercentEscape是错用的URLEncode,看看AFN和Facebook吧
别再使用stringByAddingPercentEscapesUsingEncoding 当遇到发送网络请求的参数中有汉字的情况,很多人一股脑地使用stringByAddingPercentEsca ...
- AFN和ASI区别
AFN和ASI区别 一.AFN和ASI的区别 1.底层实现1> AFN的底层基于OC的NSURLConnection和NSURLSession2> ASI的底层基于纯C语言的CFNetwo ...
- AFN框架内部结构
AFN结构体 - NSURLConnection + AFURLConnectionOperation + AFHTTPRequestOperation + AFHTTPRequestOperatio ...
随机推荐
- 九度OJ 1131:合唱队形 (DP、最长上升下降序列)
时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:2865 解决:881 题目描述: N位同学站成一排,音乐老师要请其中的(N-K)位同学出列,使得剩下的K位同学不交换位置就能排成合唱队形. ...
- 九度OJ 1084:整数拆分 (递归)
时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:2274 解决:914 题目描述: 一个整数总可以拆分为2的幂的和,例如: 7=1+2+4 7=1+2+2+2 7=1+1+1+4 7=1+1 ...
- 5.JavaScript改变样式,验证用户输入
① x=document.getElementById("demo") //找到元素 x.style.color="#ff0000"; //改变样式 ② if ...
- selenium2 python范例
selenium2 python范例 下面脚本的功能是:打开谷歌浏览器-->跳转到某个网址-->输入用户名和密码登录-->读取页面内的数据并求和. # coding=utf-8 #编 ...
- zk使用通知移除节点
前面:https://www.cnblogs.com/toov5/p/9899238.html 服务发生宕机 咋办? 发个事件通知,告知大家哟, 会有通知事件哦 看项目: 服务端: package c ...
- .PHP生成静态html文件的方法
1. [代码][PHP]代码 1,下面使用模版的一个方法! <?php $fp = fopen ("templets.html","a"); ...
- codeforces C. Inna and Huge Candy Matrix 解题报告
题目链接:http://codeforces.com/problemset/problem/400/C 题目意思:给出一个n行m列的矩阵,问经过 x 次clockwise,y 次 horizontal ...
- git bash使用端口转发连接服务器
之前的配置是 url = user@xx.xx.xx.xx:/home/tutu/thelib/ww.git xx.xx.xx.xx是服务器的外网地址,其内网地址是zz.zz.zz.zz 但是现在服务 ...
- Python: PS 图像调整--饱和度调整
本文用 Python 实现 PS 图像调整中的饱和度调整算法,具体的算法原理和效果可以参考之前的博客: http://blog.csdn.net/matrix_space/article/detail ...
- https证书自签
https http over ssl = https 443/tcp ssl: v3 tls: ...