1

I'm working with AFNetworking to get some JSON from the web. How can I get the response from the asynchronous request returned? Here's my code:

- (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;
    }
4

1 回答 1

3

I think you are confused about how blocks work.

That's an asynchronous request, therefore you cannot return any value computed inside the completion block, since your method already returned when it's executed.

You have to change your design an either perform a callback from inside the success block, or pass your own block and get it called.

As an example

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

You will then call this method like follows

[self descargarEncuestasParaCliente:clientId success:^(id JSON) {
    // Use JSON
} failure:^(NSError *error) {
    // Handle error
}];
于 2013-06-24T15:08:56.183 回答