ios - AFNetworking:重试操作时访问完成处理程序

标签 ios networking afnetworking

给出一些上下文:我正在尝试为身份验证错误实现一个全局错误处理程序(使用 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 to self, 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/

相关文章:

ios - 如何制作兼容的密码扩展?

python - 如何从谷歌云转发规则IP地址绑定(bind)发送?

ios - AFNetworking SSL 请求

ios - dequeueReusableCellWithIdentifier :forIndexPath: VS dequeueReusableCellWithIdentifier:

iphone - 试图让网络错误警报正确显示在 iPhone 应用程序上?

ios - NSFetchedResultsController 用于在 Apple Watch 上显示记录?

C++ UDP套接字以一定频率破坏数据包

c++ - WinSock c++ inet_ntop 总是显示 204.204.204.204(并且 accept() 没有失败)

ios - AFOAuth2Client 无法访问资源

ios - AFNetworking - 获取响应内容长度