Bruno
Bruno

Reputation: 1032

About AFNetworking 2

How can I dynamically change the block AFHTTPRequestOperationManager to POST, GET, DELETE...

The original example already has the http method fixed has POST:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"foo": @"bar"};
    [manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

What I wanna know, Is there a way to insert the http method dynamically? dummy example:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"foo": @"bar"};
  -->  [manager @"POST or GET or DELETE":@"http://example.com/resources.json" parameters:parameters <---success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

Sorry if I'm making a dumb question.

Best Regards.

Upvotes: 1

Views: 267

Answers (1)

Blake Schwendiman
Blake Schwendiman

Reputation: 452

Yes this is possible. You need to set up the NSURLRequest (or NSMutableURLRequest) yourself:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// set up custom reqeust serializer here, if needed
NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"GET" URLString:[NSURL URLWithString:@"http://example.com/resources.json"] parameters:parameters error:nil];
[manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

I haven't run this code as-is, but you see the general idea. If you are using a custom request serializer, you would want to set that up as indicated in the comment above.

Simply replace @"GET" with @"POST" or "@DELETE".

Upvotes: 1

Related Questions