Reputation: 199
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
Upvotes: 0
Views: 1510
Reputation: 852
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];
Upvotes: 0
Reputation: 1379
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];
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];
Upvotes: 2
Reputation: 77661
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
.
Upvotes: 0