2013-06-24 6 views
1

AFNetworking과 협력하여 웹에서 일부 JSON을 얻으려고합니다. 반환 된 비동기 요청의 응답을 어떻게 얻을 수 있습니까? 내 코드는 다음과 같습니다.AFJSONRequestOperation이 완료되기를 기다리는 중

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

답변

3

블록 작동 방식에 대해 혼란스러워합니다.

이것은 비동기식 요청이므로 완료 블록 내에서 계산 된 값은 반환 할 수 없습니다. 메서드가 실행될 때 이미 반환 되었기 때문입니다.

당신은 디자인을 변경해야 성공 블록 내부에서 콜백을 수행하거나 자신의 블록을 전달하고 호출해야합니다. 예제 코드에 대한

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

덕분에 다음과 같은 예를 들어

것은

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

당신은이 메소드를 호출합니다! 그러나 함수의 반환 형식이 void로 변경되지 않습니까?이 경우에는? –

+0

당신은 절대적으로 맞습니다 –

+0

나는 그렇게 생각했습니다. 귀하의 구현은 실제로 효과가있었습니다. 고마워요! :) –

관련 문제