Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

ios - Replacement for AFJSONRequestOperation in AFNetworking 2.x

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

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...