在进行API请求时,会遇到Token过期的情况,解决这个问题有几种办法,一种常用?方法是在回调里面检查是否过期,如果过期了,重新向服务器请求新的token,但这样不免显得繁琐,其实利用block可以换一种方法,今天在stackoverflow上看到的,就是重写AFURLSessionManager 中的dataTask方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)urlRequest completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))originalCompletionHandler{
//create a completion block that wraps the original
void (^authFailBlock)(NSURLResponse *response, id responseObject, NSError *error) = ^(NSURLResponse *response, id responseObject, NSError *error)
{
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if([httpResponse statusCode] == 401){
NSLog(@"401 auth error!");
//since there was an error, call you refresh method and then redo the original task
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
//call your method for refreshing OAuth tokens. This is an example:
[self refreshAccessToken:^(id responseObject) {
NSLog(@"response was %@", responseObject);
//store your new token
//now, queue up and execute the original task
NSURLSessionDataTask *originalTask = [super dataTaskWithRequest:urlRequest completionHandler:originalCompletionHandler];
[originalTask resume];
}];
});
}else{
NSLog(@"no auth error");
originalCompletionHandler(response, responseObject, error);
}
};
NSURLSessionDataTask *task = [super dataTaskWithRequest:urlRequest completionHandler:authFailBlock];
return task;
}

简单解释下就是将原来的回调block中添加一个检测response是否返回的是token过期的步骤,如果是,则再一次发送原来的请求,并利用原来的success的回调和fail的回调,这样封装完后,调用网络方法的时候就不会察觉到有自动更新token这一个步骤。

原文链接:http://stackoverflow.com/questions/12893837/afnetworking-handle-error-globally-and-repeat-request

SEO: AFNetworking 自动更新Token,iOS,Objective-C, refresh token automatically