2014-02-07 38 views
4

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

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

[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:^{} 
}]; 

有没有什么办法再次启动任务?

谢谢!

回答

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 
+0

非常有趣。不幸的是,如果您在请求HTTPBody中传递令牌,它将不起作用。 – Martin

+0

Martin,请不要在请求正文中传递HTTP身份验证数据。这真的是错误的! – Segabond

+0

非常感谢您的回答,它帮助了很多!但要小心,你回来的可能不是真正的'NSURLSessionDataTask' –

相关问题