AFNetworking:全局处理错误并重复请求 [英] AFNetworking: Handle error globally and repeat request

查看:496
本文介绍了AFNetworking:全局处理错误并重复请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,该用例应该相当普遍,但是我找不到使用AFNetworking处理它的简单方法:

I have a use case that should be rather common but I can't find an easy way to handle it with AFNetworking:

无论服务器何时为任何请求返回特定的状态代码,我都希望:

Whenever the server returns a specific status code for any request, I want to:

  • 删除缓存的身份验证令牌
  • 重新认证(这是一个单独的请求)
  • 重复失败的请求.

我认为可以通过AFHTTPClient中的某些全局完成/错误处理程序来完成此操作,但是我没有发现任何有用的东西.那么,做我想做的正确"方法是什么?覆盖我的AFHTTPClient子类中的enqueueHTTPRequestOperation:,复制该操作,并用一个执行我想要的功能的块包装原始完成处理程序(重新验证,使复制的操作入队)?还是我完全走错了路?

I thought that this could be done via some global completion/error handler in AFHTTPClient, but I didn't find anything useful. So, what's the "right" way to do what I want? Override enqueueHTTPRequestOperation: in my AFHTTPClient subclass, copy the operation and wrap the original completion handler with a block that does what I want (re-authenticate, enqueue copied operation)? Or am I on the wrong track altogether?

谢谢!

删除了对401状态代码的引用,因为当我使用令牌身份验证时,这可能是为HTTP基本代码保留的.

Removed reference to 401 status code, since that's probably reserved for HTTP basic while I'm using token auth.

推荐答案

在AFHTTPClient的init方法中注册AFNetworkingOperationDidFinishNotification,该请求将在请求完成后发布.

In the AFHTTPClient's init method register for the AFNetworkingOperationDidFinishNotification which will be posted after a request finishes.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HTTPOperationDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil];

在通知处理程序中,检查状态码并copy AFHTTPRequestOperation或创建一个新代码.

In the notification handler check the status code and copy the AFHTTPRequestOperation or create a new one.

- (void)HTTPOperationDidFinish:(NSNotification *)notification {
  AFHTTPRequestOperation *operation = (AFHTTPRequestOperation *)[notification object];

    if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
        return;
    }

    if ([operation.response statusCode] == 401) {
        // enqueue a new request operation here
    }
}

通常,您不需要这样做,而只需使用此AFNetworking方法处理身份验证:

In general you should not need to do that and just handle the authentication with this AFNetworking method:

- (void)setAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;

这篇关于AFNetworking:全局处理错误并重复请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆