2 alllllllll alllllllll 于 2013.06.25 11:25 提问

等待AFJSONRequestOperation完成

使用AFNetworking获取网站的一些JSON信息,如何从asynchronou请求返回得到响应?

- (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个回答

zhanglei5415
zhanglei5415   Rxr 2013.06.25 14:29
已采纳

因为是异步执行的关系,显然你这样返回肯定不能及时得到结果。
你可以将你的方法使用block改造一下

- (void) descargarEncuestasParaCliente:(NSString *)id_client block:(void(^)(id json))processResult{

        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://whatever.com/api/&id_cliente=%@", id_client]]];    
        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            processResult(JSON);  ///回调处理返回的json结果
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            NSLog(@"ERROR: %@", error);
        }];

        [operation start];
    }

调用:

[self descargarEncuestasParaCliente:@"1" block:^(id json) {
      NSLog(@"return result is :%@",json);
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!