2013-06-24 187 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

我覺得你對塊的工作方式感到困惑。

這是一個異步請求,因此您無法返回在完成塊內計算出的任何值,因爲您的方法在執行時已經返回。

你必須改變你的設計,要麼從成功塊內執行回調,要麼傳遞你自己的塊,並讓它調用。

舉個例子

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

感謝您的示例代碼!但是,在這種情況下,函數的返回類型是否會變爲void? –

+0

你絕對正確 –

+0

我是這麼想的。你的實現確實有效。非常感謝! :) –