AFNetworking:创建POST请求,但不运行

时间:2014-09-09 06:47:27

标签: ios objective-c afnetworking afnetworking-2

我试图在AFNetworking 2.0中创建POST请求:

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) {

}];

但是如何在不立即执行的情况下创建AFHTTPRequestOperation? (我需要将此操作添加到NSOperationQueue)

更新

谢谢!我最终得到了这样的解决方案:

 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 个答案:

答案 0 :(得分:2)

直接从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];

修改

如果您要将此操作提交至NSOperationQueue,则可以使用AFHTTPRequestOperationManager,如下所示

requestManager = [AFHTTPRequestOperationManager manager];

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

答案 1 :(得分:0)

NSOperationQueue添加内容的最佳方式是继承NSOperation

整个地方都有教程...... First example I found with a Google search

您的子类可能被称为MyPostOperation

它有执行POST请求的单一任务。

然后由NSOperationQueue管理并运行。

答案 2 :(得分:0)

试试这个

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