Dan*_*Dan 7 block ios 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];
}
Run Code Online (Sandbox Code Playgroud)
但是,我需要在返回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 ...
}];
}
Run Code Online (Sandbox Code Playgroud)
但现在没有回调getDevices().那么如何在getDevices中处理json对象并在完成时返回块?感谢帮助,因为我是新手.
Fel*_*lix 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);
}];
}
Run Code Online (Sandbox Code Playgroud)
编辑:
根据您发布的代码,我认为以下界面会更清晰:
typedef void(^tFailureBlock)(NSError *error);
- (void)getDevicesForUserID:(NSString *)userID
success:(void (^)(NSArray* devices))successBlock
failure:(tFailureBlock)failureBlock;
Run Code Online (Sandbox Code Playgroud)