AFNetworking

AFNetworking是一个讨人喜欢的网络库,适用于iOS以及Mac OS X. 它构建于在NSURLConnectionNSOperation, 以及其他熟悉的Foundation技术之上. 它拥有良好的架构,丰富的api,以及模块化构建方式,使得使用起来非常轻松.例如,他可以使用很轻松的方式从一个url来得到json数据:

 
1
NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/public_timeline.json"];
2
NSURLRequest *request = [NSURLRequest requestWithURL:url];
3
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
4
    NSLog(@"Public Timeline: %@", JSON);
5
} failure:nil];
6
[operation start];

如何开始使用

综述

CORE:

AFURLConnectionOperation:一个 NSOperation 实现了NSURLConnection 的代理方法.

HTTP Requests:

AFHTTPRequestOperation:AFURLConnectionOperation的子类,当request使用的协议为HTTP和HTTPS时,它压缩了用于决定request是否成功的状态码和内容类型.

AFJSONRequestOperation:AFHTTPRequestOperation的一个子类,用于下载和处理jason response数据.

AFXMLRequestOperation:AFHTTPRequestOperation的一个子类,用于下载和处理xml response数据.

AFPropertyListRequestOperation:AFHTTPRequestOperation的一个子类,用于下载和处理property list response数据.

HTTP CLIENT:

AFHTTPClient:捕获一个基于http协议的网络应用程序的公共交流模式.包含:

  • 使用基本的url相关路径来只做request
  • 为request自动添加设置http headers.
  • 使用http 基础证书或者OAuth来验证request
  • 为由client制作的requests管理一个NSOperationQueue
  • 从NSDictionary生成一个查询字符串或http bodies.
  • 从request中构建多部件
  • 自动的解析http response数据为相应的表现数据
  • 在网络可达性测试用监控和响应变化.

IMAGES

AFImageRequestOperation:一个AFHTTPRequestOperation的子类,用于下载和处理图片.

UIImageView+AFNetworking:添加一些方法到UIImageView中,为了从一个URL中异步加载远程图片

例子程序

XML REQUEST

 
1
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]];
2
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
3
  XMLParser.delegate = self;
4
  [XMLParser parse];
5
} failure:nil];
6
[operation start];

IMAGE REQUEST

 
1
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
2
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];

API CLIENT REQUEST

 
1
// AFGowallaAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates
2
[[AFGowallaAPIClient sharedClient] getPath:@"/spots/9223" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
3
    NSLog(@"Name: %@", [responseObject valueForKeyPath:@"name"]);
4
    NSLog(@"Address: %@", [responseObject valueForKeyPath:@"address.street_address"]);
5
} failure:nil];

FILE UPLOAD WITH PROGRESS CALLBACK

 
01
NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
02
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
03
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
04
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
05
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
06
}];
07
 
08
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
09
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
10
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
11
}];
12
[operation start];

STREAMING REQUEST

 
1
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];
2
 
3
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
4
operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
5
operation.outputStream = [NSOutputStream outputStreamToMemory];
6
[operation start];

转载自:http://blog.sina.com.cn/s/blog_719d537e01017x82.html


AFNetwork是一个轻量级的网络请求api类库。是以NSURLConnection, NSOperation和其他方法为基础的。


下面这个例子是用来处理json请求的:
NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"App.net Global Stream: %@", JSON);
} failure:nil];
[operation start];


使用方法:
1.下载AFNetwork, 点击下载
2.将文件夹名称为AFNetworking拖入到你的工程项目即可

常见问题:
1.  AFNetworking作用都有哪些?
NSURLConnection提供了+sendAsynchronousRequest:queue:completionHandler:和+sendAsynchronousRequest:queue:completionHandler: ,但是AFNetworking提供了更好的功能
*AFURLConnectionOperation和它的子类继承NSOperation的,允许请求被取消,暂停/恢复和由NSOperationQueue进行管理。
*AFURLConnectionOperation也可以让你轻松得完成上传和下载,处理验证,监控上传和下载进度,控制的缓存。
*AFHTTPRequestOperation和它得子类可以基于http状态和 内容列下来区分是否成功请求了
*AFNetworking可以将远程媒体数据类型(NSData)转化为可用的格式,比如如JSON,XML,图像和plist。
*AFHTTPClient提供了一个方便的网络交互接口,包括默认头,身份验证,是否连接到网络,批量处理操作,查询字符串参数序列化,已经多种表单请求
*的UIImageView+ AFNetworking增加了一个方便的方法来异步加载图像。

2. AFNetworking是否支持缓存?
可以,NSURLCache及其子类提供了很多高级接口用于处理缓存
如果你想将缓存存储再磁盘,推荐使用SDURLCache

3.如何使用AFNetworking上传一个文件?
NSData *imageData = UIImagePNGRepresentation(image);
NSURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) {
  [formData appendPartWithFileData:imageData mimeType:@"image/png" name:@"avatar"];
}];


4.如何使用AFNetworking下载一个文件?
先创建一个 AFURLConnectionOperation对象,然后再使用它的属性 outputStream进行处理
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:@"download.zip" append:NO];

5.如何解决:SystemConfiguration framework not found in project
请导入:
#import <SystemConfiguration/SystemConfiguration.h>
#import <MobileCoreServices/MobileCoreServices.h>

6.当应用程序退出时,如何保持持续的请求?
AFURLConnectionOperation有一个叫 setShouldExecuteAsBackgroundTaskWithExpirationHandler:的方法用于处理在应用程序进入后台后,进行持续的请求
[self setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
}];



一些实例:
1.XML 请求
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]];
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
  XMLParser.delegate = self;
  [XMLParser parse];
} failure:nil];
[operation start];


2.图片请求:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];

3.图片上传处理,监测上传状态:
didiwei  17:28:57
NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation start];


4.在线流媒体请求
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
operation.outputStream = [NSOutputStream outputStreamToMemory];
[operation start];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值