Iphone 正在等待AFJSONRequestOperation完成
我正在与AFNetworking合作,从web上获取一些JSON。如何从返回的异步请求中获取响应?这是我的密码:Iphone 正在等待AFJSONRequestOperation完成,iphone,ios,objective-c,afnetworking,Iphone,Ios,Objective C,Afnetworking,我正在与AFNetworking合作,从web上获取一些JSON。如何从返回的异步请求中获取响应?这是我的密码: - (id) descargarEncuestasParaCliente:(NSString *)id_client{ NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://whatever.com/a
- (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;
}
我想你对积木的工作原理感到困惑 这是一个异步请求,因此您不能返回在完成块内计算的任何值,因为您的方法在执行时已返回 您必须更改设计,或者从成功块内部执行回调,或者传递您自己的块并调用它 例如
- (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
}];
谢谢你的示例代码!但是,在这种情况下,函数的返回类型不会变为void吗?我想是的。您的实现实际上起了作用。非常感谢!:)