replaceAFNetworking 2.x中的AFJSONRequestOperation

我正在做一个基本的iPhone应用程序与HTML请求,按照本教程。

本教程让我在AFNetworking中使用AFJSONRequestOperation。 麻烦的是,我正在使用AFNetworking版本2,它不再有AFJSONRequestOperation。

所以,当然,这个代码(从教程中的“ 查询iTunes StoresearchAPI ”标题下的大约一半)不能编译:

NSURL *url = [[NSURL alloc] initWithString: @"http://itunes.apple.com/search?term=harry&country=us&entity=movie"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { NSLog(@"%@", JSON); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo); }]; [operation start]; 

我的问题是,我该如何取代AFJSONRequestOperation,以便继续使用AFNetworking 2.x? 我GOOGLE了这一点,发现没有人似乎在问这个问题。

你可以使用AFHTTPSessionManger吗? 所以像

 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; [manager GET:[url absoluteString] parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(NSURLSessionDataTask *task, NSError *error) { // Handle failure }]; 

另一种方法是使用AFHTTPRequestOperation并再次将responseSerializer设置为[AFJSONResponseSerializer serializer] 。 所以像

 AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; operation.responseSerializer = [AFJSONResponseSerializer serializer]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation , id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // Handle error }]; 

从NSHipster的文章AFNetworking 2 :

AFNetworking 2.0新架构的突破之一是使用串行器来创build请求和parsing响应。 串行器的灵活devise允许将更多的业务逻辑传送到networking层,并且可以轻松定制先前内置的默认行为。

在AFNetworking 2中,序列化程序(将HTTP数据转换为可用的Objective C对象的对象)现在是与请求操作对象分离的对象。

AFJSONRequestOperation等因此不再存在。

从AFJSONResponseSerializer文档 :

AFJSONResponseSerializerAFJSONResponseSerializer的一个子类,用于validation和解码JSON响应。

有几种方法可以击中你提到的API。 这里有一个:

 NSURL *url = [[NSURL alloc] initWithString:@"http://itunes.apple.com/search?term=harry&country=us&entity=movie"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"success: %@", operation.responseString); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"error: %@", operation.responseString); }]; [operation start];