0
votes

I'm trying to create POST request in AFNetworking 2.0:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

AFHTTPRequestOperation *operation = [manager POST: requestURL parameters:params 
 success:^(AFHTTPRequestOperation *operation, id responseObject) {

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}];

But how I can create AFHTTPRequestOperation without executing it immediately? ( I need to add this operation to NSOperationQueue )

UPDATE:

Thanks! I ended up with such solution:

 NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod: @"POST" URLString: @"website" parameters: params error: nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}];

[operation start]; // or add operation to queue
3

3 Answers

2
votes

Straight from the docs

NSURL *URL = [NSURL URLWithString:@"http://example.com/foo.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

operation.responseSerializer = [AFJSONResponseSerializer serializer];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@", responseObject);
    } failure:nil];

[operation start];

Edit

If you want to submit this operation to NSOperationQueue, you can use AFHTTPRequestOperationManager as follows

requestManager = [AFHTTPRequestOperationManager manager];

// instead of [operation start]
[requestManager.operationQueue addOperation:operation];
0
votes

The best way to add something to an NSOperationQueue is to subclass NSOperation.

There are tutorials all over the place... First example I found with a Google search.

You subclass might be called MyPostOperation.

And it has the single task of running your POST request.

It then gets managed and run by your NSOperationQueue.

0
votes

Try this

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer] 

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"%@", responseObject);
} failure:nil];
// Add the operation to a queue
// It will start once added
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperation:operation];