alllllllll 2013-06-25 03:25 采纳率: 0%
浏览 3506
已采纳

等待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条回答

  • ReyZhang 移动开发领域新星创作者 2013-06-25 06: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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元