AFNetworking 2.0 新特性讲解之AFHTTPSessionManager

时间:2021-09-14 07:35:24

AFNetworking 2.0 新特性讲解之AFHTTPSessionManager

AFNetworking 2.0 新特性讲解之AFHTTPSessionManager (2014-02-17 11:56:24)

   

AFNetworking 2.0 相比1.0 API 接口改动还是很大的. 其中一个便是 AFURLSessionManager,当然如果你不太熟悉,或者为了兼容低版本,你依然可以选择AFHTTPRequestOperationManager,AFURLSessionManager是基于

NSURLSessionConfiguration(IOS 7.0+, MAC OX10_9+)的.

下面我们借用TuneStore的API 来完成AFURLSessionManager的讲解.

如果您在看这边文章之前 我建议您首先阅读下AFNetworking2.0的官方新特性介绍.

  1. AFNetworking 2.0 Migration Guide - 你如果之前用过AF1.0 这个是很有必要来看的.
  2. AFNetworking 2.0 Docs
  3. AFNetworking 2.0 Source

另外T*witer 上说NSHipster的AFNetworking现在翻译成中文了,所以我搬过来了有兴趣的朋友也可以去看下,https://github.com/NSHipster/articles/blob/zh-Hans/2013-09-16-afnetworking-2.md

1:创建 client search iTunes

 
#import "AFHTTPSessionManager.h"
@interface ITunesClient : AFHTTPSessionManager
+ (ITunesClient *)sharedClient;
- (NSURLSessionDataTask *)searchForTerm:(NSString *)term completion:( void (^)(NSArray *results, NSError *error) )completion;
@end
 
#import "ITunesClient.h"

@implementation ITunesClient

+ (ITunesClient *)sharedClient {
static ITunesClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURL *baseURL = [NSURL URLWithString:@"https://itunes.apple.com/"]; NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setHTTPAdditionalHeaders:@{ @"User-Agent" : @"TuneStore iOS 1.0"}];

        //设置我们的缓存大小 其中内存缓存大小设置10M  磁盘缓存5M NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:10 * 1024 * 1024
diskCapacity:50 * 1024 * 1024
diskPath:nil]; [config setURLCache:cache]; _sharedClient = [[ITunesClient alloc] initWithBaseURL:baseURL
sessionConfiguration:config];
_sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
}); return _sharedClient;
} - (NSURLSessionDataTask *)searchForTerm:(NSString *)term completion:( void (^)(NSArray *results, NSError *error) )completion {
NSURLSessionDataTask *task = [self GET:@"/search"
                                  //为了速度我们将地区设置为* parameters:@{ @"country" : @"TW",
@"term" : term }
success:^(NSURLSessionDataTask *task, id responseObject) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
if (httpResponse.statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(responseObject[@"results"], nil);
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, nil);
});
NSLog(@"Received: %@", responseObject);
NSLog(@"Received HTTP %d", httpResponse.statusCode);
} } failure:^(NSURLSessionDataTask *task, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, error);
});
}];
return task;
}
@end

Note:为了便于对这个任务进行(取消,监控等)操作 我们将这个任务返回.

2: 在view controller对client进行回调

 
 NSURLSessionDataTask *task = [[ITunesClient sharedClient] searchForTerm:term
completion:^(NSArray *results, NSError *error) {
if (results) {
self.results = results;
[self.tableView reloadData];
} else {
NSLog(@"ERROR: %@", error);
}
}];

3:  AFNetworking UIKit 之 加载网络图片

每一个cell 我们可以利用 AFNetworking对UIImageView的 category .只需要在文件中导入 #import "UIImageView+AFNetworking.h" ,然后 cellForRowAtIndexPath:方法下直接使用即可

    cell.artworkImageView.image = nil;
[cell.artworkImageView cancelImageRequestOperation]; NSURL *imageURL = [NSURL URLWithString:record[@"artworkUrl100"]];
if (imageURL) {
[cell.artworkImageView setImageWithURL:imageURL];
}

4:当任务运行时显示 activity indicator

导入 #import "UIActivityIndicatorView+AFNetworking.h" 
 
[self.activityIndicator setAnimatingWithStateOfTask:task];

运行效果如下

AFNetworking 2.0 新特性讲解之AFHTTPSessionManager