搞了两年多iOS开发了,网络请求这块儿,一直用的ASIHttpRequest,但是这个开源项目好长时间不维护。据说现在这块儿都兴用了AFNetwork了,学习学习,整理资料如下:
话说我学习那天(1.21)正值github被墙之日,真纠结。所以文章最下面会搁一个AFNetwork的下载地址。ok,let’s go
1.首先要把AFNetwork导入到你的工程中 就是那19个文件afnetworking 文件夹
2.然后还要在工程里面引出2个新的framwork,SystemConfiguration和MobileCoreServices
3.很重要的一步在你的”YOURPROJECTNAME-Prefix.pch”文件里添加
#import
#import
基本上就是这样子,然后你就可以使用了.你的工程需要什么功能就在你的class里面的头文件添加什么功能的引用
如果你出现了下面AFNETWORKING的警告的话请重复安装上面的
#else
#warning SystemConfiguration framework not found in project, or not included in precompiled header. Network reachability functionality will not be available.
#endif
#ifndef __UTTYPE__
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#warning MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.
#else
#warning CoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.
#endif
#endif
常用方法举例:
1.较底层的一个封装
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/ip"]];
AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request];
operation.completionBlock = ^ {
NSLog(@"Complete: %@", operation.responseString);
};
[operation start];
2.基于上一个东东更高一层的封装
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/robots.txt"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", error);
}];
[operation start];
3.处理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];
4.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];
5.图片请求:
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"]];
6.图片上传处理,监测上传状态:
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 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];
7.在线流媒体请求
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];
常见问题:
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 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
#import
6.当应用程序退出时,如何保持持续的请求?
AFURLConnectionOperation有一个叫setShouldExecuteAsBackgroundTaskWithExpirationHandler:的方法用于处理在应用程序进入后台后,进行持续的请求
[self setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
}];