首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重新运行失败的NSURLSessionTask

重新运行失败的NSURLSessionTask
EN

Stack Overflow用户
提问于 2014-02-07 00:53:58
回答 1查看 1.7K关注 0票数 4

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

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

代码语言:javascript
复制
[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请求失败,因为我后端的用户的auth令牌是。所以我想要做的是运行一个重新认证块,看看我们是否可以再次登录。就像这样:

代码语言:javascript
复制
[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:^{}
}];

有什么办法重新开始这个任务吗?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-27 23:01:30

如果还有人对此感兴趣,我最终通过子类HTTPSessionManager来实现解决方案,如下所示:

代码语言:javascript
复制
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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21617294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档