【问题标题】:How to get response value from NSObject class through AFNetworking?如何通过 AFNetworking 从 NSObject 类获取响应值?
【发布时间】:2015-06-16 15:27:11
【问题描述】:

我正在按照本教程学习 IOS 中的 AfNetworking 并且我正在使用以下函数从服务器获取响应:

例如,我有一个返回值的方法:

{
    __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 返回。我不知道语法。有人可以帮我吗?

【问题讨论】:

    标签: ios objective-c afnetworking objective-c-blocks


    【解决方案1】:

    当然……您可能不需要将 NSDictionary 声明为块对象:

    {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *response = (NSDictionary *)responseObject;
            ...
        }
    }
    

    【讨论】:

      【解决方案2】:

      在成功块之外返回响应将只包含您初始化的空白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'
      }];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-25
        • 1970-01-01
        相关资源
        最近更新 更多