重新运行失败的NSURLSessionTask

时间:2014-02-07 00:53:59

标签: ios afnetworking-2 nsurlsession

我想知道是否有可能重新运行失败的NSURLSessionDataTask。以下是我遇到此问题的背景。

我有一个使用AFNetworking 2.0来处理请求的Web服务对象。在我的一种方法中,我有这个:

[HTTPSessionManager GET:path parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {

} failure:^(NSURLSessionDataTask *task, NSError *error) {
    //sometimes we fail here due to a 401 and have to re-authenticate.
}];

现在,有时GET请求失败,因为我后端的用户身份验证令牌是。所以我想要做的是运行重新认证块,看看我们是否可以再次登录。像这样:

[HTTPSessionManager GET:path parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {

} failure:^(NSURLSessionDataTask *task, NSError *error) {
    if (task.response.statusCode == 401)
       RunReAuthenticationBlockWithSuccess:^(BOOL success) {
           //somehow re-run 'task'
        } failure:^{}
}];

有没有办法重新开始这项任务?

谢谢!

1 个答案:

答案 0 :(得分:3)

如果有人仍然感兴趣,我最后通过继承HTTPSessionManager来实现我的解决方案,如下所示:

typedef void(^AuthenticationCallback)(NSString *updatedAuthToken, NSError *error);
typedef void(^AuthenticationBlock)(AuthenticationCallback);


@interface MYHTTPSessionManager : AFHTTPSessionManager
@property (nonatomic, copy) AuthenticationBlock authenticationBlock;
@end

@implementation MYHTTPSessionManager


- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler {

void (^callback)(NSString *, NSError *) = ^(NSString *tokenString, NSError *error) {
    if (tokenString) {
        //ugh...the request here needs to be re-serialized. Can't think of another way to do this
        NSMutableURLRequest *mutableRequest = [request mutableCopy];
        [mutableRequest addValue:AuthorizationHeaderValueWithTokenString(tokenString) forHTTPHeaderField:@"Authorization"];
        NSURLSessionDataTask *task = [super dataTaskWithRequest:[mutableRequest copy] completionHandler:completionHandler];
        [task resume];
    } else {
        completionHandler(nil, nil, error);
    }
};

void (^reauthCompletion)(NSURLResponse *, id, NSError *) = ^(NSURLResponse *response, id responseObject, NSError *error){

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSInteger unauthenticated = 401;
    if (httpResponse.statusCode == unauthenticated) {
        if (self.authenticationBlock != NULL) {
            self.authenticationBlock(callback); return;
        }
    }

    completionHandler(response, responseObject, error);
};

return [super dataTaskWithRequest:request completionHandler:reauthCompletion];
}

@end
相关问题