AFJSONRequestOperation

AFJSONRequestOperation

本文介绍了在AFNetworking 2.x中替换AFJSONRequestOperation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个包含HTML请求的基本iPhone应用程序,方法是

I am making a basic iPhone app with HTML Requests, by following this tutorial.

本教程让我在AFNetworking中使用AFJSONRequestOperation。问题是,我正在使用AFNetworking版本2,它不再具有AFJSONRequestOperation。

The tutorial has me using AFJSONRequestOperation in AFNetworking. The trouble is, I'm using AFNetworking version 2, which no longer has AFJSONRequestOperation.

所以,当然,这段代码(从教程的大约一半开始,在查询iTunes Store搜索API 标题下无法编译:

So, of course, this code (from about half-way down the tutorial, under the heading "Querying the iTunes Store Search API") doesn't compile:

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搜索了一下,发现其他人似乎都没有问这个问题。

My question is, what do I replace AFJSONRequestOperation with so that I can keep working with AFNetworking 2.x? I've googled this and found that no one else seems to be asking this question.

推荐答案

你能使用AFHTTPSessionManger吗?所以类似

Could you use AFHTTPSessionManger? So something like

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序列化程序] 。所以类似

Another alternative could be to use AFHTTPRequestOperation and again set the responseSerializer to [AFJSONResponseSerializer serializer]. So something like

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

这篇关于在AFNetworking 2.x中替换AFJSONRequestOperation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 07:00