使用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;
}
因為是異步執行的關系,顯然你這樣返回肯定不能及時得到結果。
你可以將你的方法使用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);
}