AFHTTPRequestOperationManager到主队列

时间:2014-07-07 05:35:32

标签: afnetworking

如何将以下代码与主队列一起运行,以便我可以先处理URL响应?

 - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

        [self method];
        **// can I manipulate the response here?**
        NSLog(@"Testing....");
    }

- (void)method {
    AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
    [operationManager POST:@"http://test.com"
                parameters:@{@"test1":@"AU", @"test2":@"1"}
                   success:^(AFHTTPRequestOperation *operation, id responseObject) {
                       NSLog(@"JSON: %@", responseObject);
                   }
                   failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                       NSLog(@"Error: %@", [error description]);
                   }
     ];
}

2 个答案:

答案 0 :(得分:1)

您可以使用AFHTTPRequestOperationManager的块版本:

__weak typeof(self) weakSelf = self;

self.getActSuccess = ^ (id responseObject)
{
    __strong typeof(self) strongSelf = weakSelf;
    // you can run following code
    [strongSelf.view XXXXX];
}

AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager POST:@"http://test.com"
            parameters:nil
               success:self.getActSuccess
               failure:nil
 ];

答案 1 :(得分:0)

(1)在Header文件[ViewController.h]中声明块,如下所示。

typedef void (^ResponseBlock)(BOOL success, id result, NSError *error);

(2)用block作为参数创建你的方法,如下所示。

 - (void)method:(ResponseBlock)completionHandler {
        AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
        [operationManager POST:@"http://test.com"
                    parameters:@{@"test1":@"AU", @"test2":@"1"}
                       success:^(AFHTTPRequestOperation *operation, id responseObject) {
                           NSLog(@"JSON: %@", responseObject);
                           completionHandler(YES,responseObject,nil);
                       }
                       failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                           NSLog(@"Error: %@", [error description]);
                           completionHandler(NO,nil,error);
                       }
         ];
}

(3)在viewDidLoad中调用如下方法。

 [self method: ^(BOOL success, id result, NSError *error) {
    if (success) {
        //Do your success task
    }
    else {
        //Else handle error
        NSLog(@"Error %@",error.localizedDescription);
    }