Replacement for AFJSONRequestOperation in AFNetworking 2.x

前端 未结 2 1528
花落未央
花落未央 2020-12-14 17:24

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

The tutorial has me using AFJSONRequestOperation in AFNetworking. The trouble

相关标签:
2条回答
  • 2020-12-14 17:56

    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
    }];
    
    0 讨论(0)
  • 2020-12-14 18:00

    From NSHipster's article on AFNetworking 2:

    One of the breakthroughs of AFNetworking 2.0's new architecture is use of serializers for creating requests and parsing responses. The flexible design of serializers allows for more business logic to be transferred over to the networking layer, and for previously built-in default behavior to be easily customized.

    In AFNetworking 2, serializers (the objects that turn HTTP data into usable Objective C objects) are now separate objects from the request operation object.

    AFJSONRequestOperation, etc. therefore no longer exist.

    From the AFJSONResponseSerializer docs:

    AFJSONResponseSerializer is a subclass of AFHTTPResponseSerializer that validates and decodes JSON responses.

    There are a few ways to hit the API you mentioned. Here's one:

    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];
    
    0 讨论(0)
提交回复
热议问题