等待AFJSONRequestOperation完成

时间:2013-06-24 15:01:49

标签: iphone ios objective-c afnetworking

我正在与AFNetworking合作,从网上获取一些JSON。如何从返回的异步请求中获取响应?这是我的代码:

- (id) descargarEncuestasParaCliente:(NSString *)id_client{

        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://whatever.com/api/&id_cliente=%@", id_client]]];

        __block id RESPONSE;

        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

            RESPONSE = JSON;

        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            NSLog(@"ERROR: %@", error);
        }];

        [operation start];

        return RESPONSE;
    }

1 个答案:

答案 0 :(得分:3)

我认为你对块的工作原理感到困惑。

这是一个异步请求,因此您无法返回在完成块内计算的任何值,因为您的方法在执行时已经返回。

你必须改变你的设计,要么从成功块内部执行回调,要么传递你自己的块并让它被调用。

作为一个例子

- (void)descargarEncuestasParaCliente:(NSString *)id_client success:(void (^)(id JSON))success failure:(void (^)(NSError *error))failure {

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://whatever.com/api/&id_cliente=%@", id_client]]];

    __block id RESPONSE;

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        if (success) {
            success(JSON);
        }

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"ERROR: %@", error);
        if (failure) {
            failure(error);
        }
    }];

    [operation start];
}

然后,您将调用此方法,如下所示

[self descargarEncuestasParaCliente:clientId success:^(id JSON) {
    // Use JSON
} failure:^(NSError *error) {
    // Handle error
}];