gpt4 book ai didi

ios - 在方法中包装来自 AFNetworking 的成功失败 block

转载 作者:可可西里 更新时间:2023-11-01 03:29:13 24 4
gpt4 key购买 nike

在编写库时,我需要将 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 对象并让 block 在完成时返回?感谢您的帮助,因为我是 block 的新手。

最佳答案

这真的很容易做到:只需像调用函数一样调用 block 即可。

- (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;

关于ios - 在方法中包装来自 AFNetworking 的成功失败 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11163546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com