What is the recommended way to intercept and prevent redirects with AFNetworking 2.0?

戏子无情 提交于 2020-01-02 10:08:22

问题


It seems to me that the proper place to do this is in AFURLSessionManager, in setting the taskWillPerformHTTPRedirection block, but I am unsure of the best way to handle it.

Currently, in my AFHTTPSessionManager subclass, I am setting the redirect block globally for all requests, and I know I can prevent redirects by returning nil here:

- (void)setupRedirectBlock {
    [self setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest *(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request) {
        return nil;
    }];
}

...but I need to only do this on specific tasks, and there doesn't appear to be a way to get this information from the task itself.

I guess I am looking for some sort of user info dictionary or something I can use to set a flag telling this method to either return the request or return nil. Currently, it looks like I would have to do a string comparison on the response/request URL in the client where it is far away from where the task and path is actually created.

So this begs the question, am I fighting convention, or is there really no better way to intercept an AFNetworking 2.0 redirect on a task-by-task basis?


回答1:


setTaskWillPerformHTTPRedirectionBlock is the best way to intercept redirects. The session manager is responsible for determining when or when not to prevent redirects based on the request associated with the task. In most cases, the path of the request should be a sufficient determination, but the user could additionally tag information in a custom request header field.




回答2:


I have the same question, but unfortunately I don't yet have a good enough answer. One workaround could be using taskDescription https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionTask_class/Reference/Reference.html#//apple_ref/occ/instp/NSURLSessionTask/taskDescription

Just put there some constant like DO_NOT_FOLLOW_REDIRECT and check for it in your setTaskWillPerformHTTPRedirectionBlock block.



来源:https://stackoverflow.com/questions/22561235/what-is-the-recommended-way-to-intercept-and-prevent-redirects-with-afnetworking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!