ios之AFN
https://github.com/AFNetworking/AFNetworking
与asi-http-request功能类似的网络库,不过是基于NSURLConnection 和 NSOperation 的,同样支持iOS与MacOS双平台。目前的更新比较频繁,适合新项目使用,而且使用起来也更简单。
操作JSON

- (IBAction)jsonTapped:(id)sender {
//
NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
//
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.weather = (NSDictionary *)JSON;
self.title = @"JSON Retrieved";
[self.tableView reloadData];
}
//
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}];
//
[operation start];
}

- 根据基本的URL构造出完整的一个URL。然后通过这个完整的URL获得一个NSURL对象,然后根据这个url获得一个NSURLRequest.
- AFJSONRequestOperation 是一个功能完整的类(all-in-one)— 整合了从网络中获取数据并对JSON进行解析。
- 当请求成功,则运行成功块(success block)。在本示例中,把解析出来的天气数据从JSON变量转换为一个字典(dictionary),并将其存储在属性 weather 中.
- 如果运行出问题了,则运行失败块(failure block),比如网络不可用。如果failure block被调用了,将会通过提示框显示出错误信息。
操作Property Lists(plists)

-(IBAction)plistTapped:(id)sender{
NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=plist",BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFPropertyListRequestOperation *operation =
[AFPropertyListRequestOperation propertyListRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) {
self.weather = (NSDictionary *)propertyList;
self.title = @"PLIST Retrieved";
[self.tableView reloadData];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[av show];
}];
[operation start];
}

上面的代码几乎与JSON版的一致,只不过将操作(operation)的类型从AFJSONOperation 修改为 AFPropertyListOperation.
操作XML

- (IBAction)xmlTapped:(id)sender{
NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=xml",BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFXMLRequestOperation *operation =
[AFXMLRequestOperation XMLParserRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
//self.xmlWeather = [NSMutableDictionary dictionary];
XMLParser.delegate = self;
[XMLParser setShouldProcessNamespaces:YES];
[XMLParser parse];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[av show];
}];
[operation start];
}

到现在为止,这看起来跟之前处理JSON和plist很类似。最大的改动就是在成功块(success block)中, 在这里不会传递给你一个预处理好的NSDictionary对象. 而是AFXMLRequestOperation实例化的NSXMLParse对象,这个对象将用来处理繁重的XML解析任务。
NSXMLParse对象有一组delegate方法是你需要实现的 — 用来获得XML数据。注意,在上面的代码中我将XMLParser的delegate设置为self, 因此WTTableViewController将用来处理XML的解析任务。
下载图片
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"]];

- (IBAction)updateBackgroundImage:(id)sender {
//Store this image on the same server as the weather canned files
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;
[self saveImage:image withFilename:@"background.png"];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Error %@",error);
}];
[operation start];
}


-(void)saveImage:(UIImage *)image withFilename:(NSString *)filename{
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:] stringByAppendingPathComponent:@"WeatherHTTPClientImages/"];
BOOL isDir;
if(![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]){
if(!isDir){
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
NSLog(@"%@",error);
}
}
path = [path stringByAppendingPathComponent:filename];
NSData *imageData = UIImagePNGRepresentation(image);
NSLog(@"Written: %d",[imageData writeToFile:path atomically:YES]);
}

AFHTTPClient
AFHTTPClient一般是给它设置一个基本的URL,然后用AFHTTPClient进行多个请求(而不是像之前的那样,每次请求的时候,都创建一个AFHTTPClient)。

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex==){
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:@"application/json"];
[client postPath:@"weather.php"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.weather = responseObject;
self.title = @"HTTP POST";
[self.tableView reloadData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}
];
}
else if (buttonIndex==){
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:@"application/json"];
[client getPath:@"weather.php"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.weather = responseObject;
self.title = @"HTTP GET";
[self.tableView reloadData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}
];
}
}

- 构建一个baseURL,以及一个参数字典,并将这两个变量传给AFHTTPClient.
- 将AFJSONRequestOperation注册为HTTP的操作, 这样就可以跟之前的示例一样,可以获得解析好的JSON数据。
- 做了一个GET请求,这个请求有一对block:success和failure。
- POST请求跟GET一样。
上传一个文件

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);
}];
[httpClient enqueueHTTPRequestOperation:operation];

下载一个文件

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];

参考:
ios之AFN的更多相关文章
- IOS开发 AFN和ASI
做项目有一段时间了,项目过程中处理网络请求难免的,而对于选择第三方来处理网络请求肯定是个明智的选择! AFNetworking和ASIHTTPRequest 这两个第三方该如何选择 我 ...
- ios之AFN上传下载详细步骤(2)
五.AFN .GET\POST > GET请求 // 1.获得请求管理者 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperation ...
- iOS 使用AFN 进行单图和多图上传 摄像头/相册获取图片,压缩图片
图片上传时必要将图片进行压缩,不然会上传失败 首先是同系统相册选择图片和视频.iOS系统自带有UIImagePickerController,可以选择或拍摄图片视频,但是最大的问题是只支持单选,由于项 ...
- iOS开发AFN使用二:AFN文件下载与文件上传
#import "ViewController.h" #import "AFNetworking.h" @interface ViewController () ...
- ios 使用AFN上传图片到服务器
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.responseSe ...
- iOS 使用AFN 进行单图和多图上传
图片上传时必要将图片进行压缩,不然会上传失败 1.单张图上传 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManag ...
- iOS之AFN错误代码1016(Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable)
请参考这篇博客:点击查看
- iOS用AFN上传图片到java后台
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { AFHTTPSessionMana ...
- iOS开发之AFN的基本使用
本篇将从四个方面对iOS开发中经常使用到的AFNetworking框架进行讲解: 一.什么是 AFN 二.为什么要使用 AFN 三.AFN 怎么用 三.AFN和ASI的区别 一.什么是 AFN AFN ...
随机推荐
- Androidstudio中添加jar包的方法
在Androidstudio中添加一个jar包进去,怎么添加? 以下纯个人使用Androidstudio过程中的经验积累,要是有不足,望提出建议. 方法一: 先点击Androidstudio中的Pro ...
- POJ1787 【完全背包+物品计数+路径输出】
题意: 有1,5,10,25四种硬币,给每种硬币的数量和要组合成的价值,求刚好达到价值时用的硬币最多,然后还要输出具体的用的数量 前言: 一开始是偶然看见了kuangbin爷的题解说是完全背包+路径, ...
- 洛谷 P4719 【模板】动态dp【动态dp】
是动态dp的板子 大致思想就是用g[u]来表示不包含重链转移的dp值,然后用线段树维护重链,这样线段树的根就相当于这条重链的top的真实dp值 每次修改的时候,修改x点会影响到x到根的真实dp值,但是 ...
- 如何使用go打出hell word
今天给大家带来一篇如何使用go打出hell word(手动滑稽) 关于go介绍的话,我就不多说了,在百度上一搜一大堆, 要使用的软件Visual Studio Code(VScode) 下载go的地址 ...
- Python递归和迭代
递归 在函数内部,调用函数自身的编程技巧称为递归( recursion).递归函数结构清晰,很直观的理解计算过程,但也有严重缺点:相对于普通循环而言,递归运行效率较低,经过很多冗余的计算,递归会消耗大 ...
- Tcp实现省略编码
import socket class My_socket(socket.socket): def __init__(self, encoding='utf-8'): self.encoding = ...
- MessageDigest简介(与MD5加密有关)
参考文章:http://blog.sina.com.cn/s/blog_4f36423201000c1e.html 参考来源:http://blog.csdn.net/hudashi/article/ ...
- PHP fgets 函数
<?php $handle=fopen("../good/html/1.txt","r"); ; //打开一个远程文件 $content="&q ...
- PowerShell~文件操作和对象遍历
ps提供了丰富的文件操作,如建立,删除,改名,移动,复制,文件夹建立,显示文件列表,同时对数组对象的遍历也很方便,如果在使用PS脚本时,希望现时传入参数,可以把参数声明为param,当然需要把它写在文 ...
- springboot项目启动问题
在调试项目的时候有遇到这样一个问题: 项目启动后访问不通,编译没有任何问题,启动也没有报错,日志在打,但是访问不通.而且之前一直可以正常访问,在没改任何代码的情况下不能访问了. 尝试很多次偶然发现,点 ...