给出一些上下文:我正在尝试为身份验证错误实现一个全局错误处理程序(使用 token 身份验证,而不是基本的),它应该尝试重新身份验证然后重复原始失败的请求(参见我之前的问题: AFNetworking: Handle error globally and repeat request )
当前的方法是为 AFNetworkingOperationDidFinishNotification
注册一个观察者,它会进行重新验证并(如果验证成功)重复原始请求:
- (void)operationDidFinish:(NSNotification *)notification
{
AFHTTPRequestOperation *operation = (AFHTTPRequestOperation *)[notification object];
if(![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
return;
}
if(403 == [operation.response statusCode]) {
// try to re-authenticate and repeat the original request
[[UserManager sharedUserManager] authenticateWithCredentials...
success:^{
// repeat original request
// AFHTTPRequestOperation *newOperation = [operation copy]; // copies too much stuff, eg. response (although the docs suggest otherwise)
AFHTTPRequestOperation *newOperation = [[AFHTTPRequestOperation alloc] initWithRequest:operation.request];
// PROBLEM 1: newOperation has no completion blocks. How to use the original success/failure blocks here?
[self enqueueHTTPRequestOperation:newOperation];
}
failure:^(NSError *error) {
// PROBLEM 2: How to invoke failure block of original operation?
}
];
}
}
但是,我偶然发现了一些关于请求操作完成 block 的问题:
当重复原始请求时,我显然希望它的完成 block 被执行。但是,
AFHTTPRequestOperation
不保留对传递的成功和失败 block 的引用(参见setCompletionBlockWithSuccess:failure:
)和复制NSOperation
的completionBlock
可能不是一个好主意,因为AFURLConnectionOperation
的文档指出:Operation copies do not include
completionBlock
.completionBlock
often strongly captures a reference toself
, which, perhaps surprisingly, would otherwise point to the original operation when copied.如果重新验证失败,我想调用原始请求的失败 block 。因此,我再次需要直接访问它。
我是不是漏掉了什么?对替代方法有什么想法吗?我应该提交功能请求吗?
最佳答案
我在 Art.sy 中遇到过这个问题的投资组合应用程序。我最终的结论是创建一个 NSOperationQueue 子类,它具有在各种 AFNetworking HTTP 操作失败后创建副本的功能(并且在放弃之前每个 URL 最多执行三次。)
关于ios - AFNetworking:重试操作时访问完成处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12951037/