在方法中包装AFNetworking的成功失败块

时间:2012-06-22 20:20:29

标签: ios block afnetworking

当我正在编写库时,我需要在我自己的方法中封装来自AFNetworking调用的响应。这段代码让我接近:

MyDevice *devices = [[MyDevice alloc] init];
  [devices getDevices:@"devices.json?user_id=10" success:^(AFHTTPRequestOperation *operation, id responseObject) {

    ... can process json object here ...

}

 - (void)getDevices:(NSString *)netPath success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure {
    [[MyApiClient sharedDeviceServiceInstance] getPath:[NSString stringWithFormat:@"%@", netPath]
      parameters:nil success:success  failure:failure];
}

但是,我需要在返回getDevices()之前处理从getPath返回的json对象数据。 我试过这个:

- (void)getDevices:(NSString *)netPath success:(void (^)(id  myResults))success
        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure {

  [[MyApiClient sharedDeviceServiceInstance] getPath:[NSString stringWithFormat:@"%@", netPath]
    parameters:nil
    success:^(AFHTTPRequestOperation *operation, id responseObject)
   {
     ... can process json object here ...
   }                           
   failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     ... process errors here ...
   }];
}

但现在没有回调getDevices()。 那么如何在getDevices&中处理json对象呢?在完成时有块返回? 感谢帮助,因为我是新手。

1 个答案:

答案 0 :(得分:10)

这很容易做到:只需通过调用它来调用块。

- (void)getDevices:(NSString *)netPath 
           success:(void (^)(id  myResults))success
           failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure
{
  [[MyApiClient sharedDeviceServiceInstance] 
     getPath:netPath
  parameters:nil
     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
       id myResults = nil;
       // ... can process json object here ...
       success(myResults);
     }                           
     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       // ... process errors here ...
       failure(operation, error);
     }];
}

修改

根据您发布的代码,我认为以下界面会更清晰:

typedef void(^tFailureBlock)(NSError *error);

- (void)getDevicesForUserID:(NSString *)userID 
                    success:(void (^)(NSArray* devices))successBlock
                    failure:(tFailureBlock)failureBlock;