网络编程第三方框架:AFNetworking、SDWebImage
介绍:这些框架是开源的,经过前人的封装、改进,成为使用次数很多的一个性能好的源代码框架,只需要将它导入项目中,就可以使用。因此,在做项目时,使用它能够大大地提高效率。
※ 一、AFNetworking:功能是用来下载网络数据(包括文件,图片等)
属性如下:
※NSURLConnection:AFURLConnectionOperationAFHTTPRequestOperationAFHTTPRequestOperationManager※ NSURLSessionAFURLSessionManagerAFHTTPSessionManager※Serialization<AFURLRequestSerialization>
AFHTTPRequestSerializerAFJSONRequestSerializer
AFPropertyListRequestSerializer
<AFURLResponseSerialization>
AFHTTPResponseSerializerAFJSONResponseSerializer
AFXMLParserResponseSerializer
AFXMLDocumentResponseSerializer
(Mac OS X)AFPropertyListResponseSerializer
AFImageResponseSerializer
AFCompoundResponseSerializer
封装的主要方法如下:
说明:`AFHTTPRequestOperationManager`封装了与web应用程序通过HTTP通信的常见模式,包括创建请求,响应序列化,网络可达性监控、运营管理和安全,以及请求。
<1> `GET` Request:get请求
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
<2>`POST` URL-Form-Encoded Request:post请求
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
<3>`POST` Multi-Part Request:post多部分的请求
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
说明:“AFURLSessionManager”创建并管理一个“NSURLSession”对象基于指定的“NSURLSessionConfiguration”对象,这符合< NSURLSessionTaskDelegate >,< NSURLSessionDataDelegate >,< NSURLSessionDownloadDelegate >,和< NSURLSessionDelegate >。
<4>Creating a Download Task:创建一个下载任务
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {NSLog(@"File downloaded to: %@", filePath);}];[downloadTask resume];
<5>Creating an Upload Task:创建一个上传任务
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {if (error) {NSLog(@"Error: %@", error);} else {NSLog(@"Success: %@ %@", response, responseObject);}}];[uploadTask resume];
<6>Creating an Upload Task for a Multi-Part Request, with Progress:创建一个多部分请求带进程的上传任务
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];} error:nil];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];NSProgress *progress = nil;NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {if (error) {NSLog(@"Error: %@", error);} else {NSLog(@"%@ %@", response, responseObject);}}];[uploadTask resume];
<7>Creating a Data Task:创建一个数据的任务
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {if (error) {NSLog(@"Error: %@", error);} else {NSLog(@"%@ %@", response, responseObject);}}];[dataTask resume];
<8>请求序列化
#### 请求序列化器创建请求URL字符串编码参数作为查询字符串或HTTP的身体。
NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
#### Query String Parameter Encoding:查询字符串参数编码
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
#### URL Form Parameter Encoding:URL形式参数编码[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];POST http://example.com/Content-Type: application/x-www-form-urlencodedfoo=bar&baz[]=1&baz[]=2&baz[]=3#### JSON Parameter Encoding:JSON参数编码[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
POST http://example.com/Content-Type: application/json
{"foo": "bar", "baz": [1,2,3]}
※ 二、SDWebImage:功能是主要用来下载和管理网络图片(也支持动态的GIF),封装的方法如下
<1> 可以结合表格使用,设置单元格图片
sd_setImageWithURL:(NSURL*)url placeholderImage:(UIImage*) image
<2> 可以结合表格使用,设置单元格图片,不过添加了block代码块
sd_setImageWithURL:(NSURL*)url placeholderImage:(UIImage*) image completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {... completion code here ...}];
<3>SDWebImageManager是类UIImageView + WebCache类别,创建管理对象,它使用异步方式下载图像数据并缓存
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadImageWithURL:imageURL
options:0
progress:^(NSInteger receivedSize, NSInteger expectedSize)
{
// progression tracking code
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL
*imageURL)
{
if (image)
{
// do something with image
}
}];
<4>创建下载对象,它独立使用异步下载图像
[SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL
options:0
progress:^(NSInteger receivedSize, NSInteger expectedSize)
{
// progression tracking code
}
completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished)
{
if (image && finished)
{
// do something with image
}
}];
<5>SDImageCache类提供了一个单例实例,创建图像缓存对象,它独立使用异步图像缓存,默认情况下SDImageCache将查找磁盘缓存如果图像不能被发现在内存缓存中,查找缓存,使用“queryDiskCacheForKey:完成:”方法。如果这个方法返回nil,这意味着缓存目前没有自己的图像。您可以通过调用替代方法来避免这个问题的发生,imageFromMemoryCacheForKey:,一个图像存储到硬盘缓存中,你使用storeImage:forKey:toDisk:
方法:
SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"myNamespace"];
[imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image)
{
// image is not nil if image was found
}];
<6>有时,您可能不希望使用图像URL缓存键,因为URL的一部分是动态的(即。访问控制的目的)。SDWebImageManager过滤器提供了一种方法来设置缓存键,需要NSURL作为输入,输出缓存键NSString。下面的示例应用程序中设置一个过滤器委托,将删除任何查询字符串URL之前使用它作为一个缓存键:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
SDWebImageManager.sharedManager.cacheKeyFilter = ^(NSURL *url)
{
url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
return [url absoluteString];
};
// Your app init code...
return YES;
}
<7>处理图像刷新:SDWebImageRefreshCached
[imageView sd_setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"]
placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"]
options:SDWebImageRefreshCached];