我正在按照本教程学习AfNetworking
中的IOS
我正在使用以下函数从服务器获取响应:
例如,我有一个返回值的方法:
{
__block id response = [[NSDictionary alloc]init];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:URLString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
response=responseObject;
NSLog(@"JSON: %@", response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
NSLog(@" return Dic ==> %@",response);
return response;
}
我想要的是编写一个函数,它会在得到响应之后将响应返回为NSDictionary
。我不知道语法。任何人都可以帮助我吗?
答案 0 :(得分:0)
当然......你可能不需要将NSDictionary声明为块对象,但是:
{
if ([responseObject isKindOfClass:[NSDictionary class]]) {
NSDictionary *response = (NSDictionary *)responseObject;
...
}
}
答案 1 :(得分:0)
在成功块之外返回响应将仅包含您初始化的空白NSDictionary
对象。封装方法可以将块作为接收响应时要执行的参数。
-(void)makeServiceCallSuccess:(void (^)(NSDictionary *response))success
failure:(void (^)(NSError *error))failure {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:URLString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
response = (NSDictionary *)responseObject;
success(response);
NSLog(@"JSON: %@", response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error);
NSLog(@"Error: %@", error);
}];
}
然后你会调用这样的方法:
[YourClass makeServiceCallSuccess:^(NSDictionary *response) {
//Do stuff with 'response'
} failure:^(NSError *error) {
//Do stuff with 'error'
}];