I need to encapsulate the response from AFNetworking calls within my own method as I'm writing a library. This code gets me close:
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];
}
However, I need to process the json object data returned from getPath before returning to getDevices(). I've tried this:
- (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 ...
}];
}
But now there is no call back to getDevices(). So how do I process the json object in getDevices & have the block return on completion? Appreciate the help, as I'm new to blocks.
That's really easy to do: Just invoke the block by calling it like a function.
- (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);
}];
}
EDIT:
Based on the code you posted I think the following interface would be more clear:
typedef void(^tFailureBlock)(NSError *error);
- (void)getDevicesForUserID:(NSString *)userID
success:(void (^)(NSArray* devices))successBlock
failure:(tFailureBlock)failureBlock;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With