gpt4 book ai didi

ios - 重新运行失败的 NSURLSessionTask

转载 作者:可可西里 更新时间:2023-11-01 05:44:34 26 4
gpt4 key购买 nike

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

我有一个 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 请求会失败,因为我后端的用户身份验证 token 是 .所以我想做的是运行一个重新验证 block ,看看我们是否可以再次登录。像这样:

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

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

谢谢!

最佳答案

如果有人仍然感兴趣,我最终通过子类化 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

关于ios - 重新运行失败的 NSURLSessionTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21617294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com