gpt4 book ai didi

ios - NSURLSessionDataTask 超时后续请求失败

转载 作者:技术小花猫 更新时间:2023-10-29 10:51:26 30 4
gpt4 key购买 nike

我正在创建一个 NSMutableRequest:

self.req = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];

超时设置为 10 秒,因为我不希望用户等待太久才能获得反馈。之后我创建了一个 NSURLSessionDataTask:

NSURLSessionDataTask *task = [self.session dataTaskWithRequest:self.req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse * httpResp = (NSHTTPURLResponse *)response;
if (error) {
// this is where I get the timeout
}
else if (httpResp.statusCode < 200 || httpResp.statusCode >= 300) {
// handling error and giving feedback
}
else {
NSError *serializationError = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&serializationError];
}
[task resume];
}

问题是服务器进入网关超时状态,这会花费很多时间。我收到超时错误并向用户提供反馈,但由于超时错误,以下所有 API 调用都以相同的方式失败。阻止它的唯一方法是终止应用程序并重新开始。在超时错误后我应该做些什么来终止任务或连接?如果我不设置超时,我等到从服务器收到错误代码,所有以下调用都可以正常工作(但用户等待了很多!)。

我试图取消任务:

NSURLSessionDataTask *task = [self.session dataTaskWithRequest:self.req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse * httpResp = (NSHTTPURLResponse *)response;
if (error) {
// this is where I get the timeout
[task cancel];
}
...
[task resume];
}

最佳答案

我没有看到你恢复你开始的任务。您需要声明:

[task resume];

此行恢复任务(如果暂停)。

尝试调用 NSURLSession 如下:

[NSURLSession sharedSessison] instead of self.session

并通过以下方式使 session 无效:

 [[NSURLSession sharedSession]invalidateAndCancel];

来自 Apple 的文档:

When your app no longer needs a session, invalidate it by calling either invalidateAndCancel (to cancel outstanding tasks) or finishTasksAndInvalidate (to allow outstanding tasks to finish before invalidating the object).

    - (void)invalidateAndCancel

Once invalidated, references to the delegate and callback objects are broken. Session objects cannot be reused.

要允许未完成的任务运行直到完成,请改为调用 finishTasksAndInvalidate。

  - (void)finishTasksAndInvalidate

This method returns immediately without waiting for tasks to finish. Once a session is invalidated, new tasks cannot be created in the session, but existing tasks continue until completion. After the last task finishes and the session makes the last delegate call, references to the delegate and callback objects are broken. Session objects cannot be reused.

要取消所有未完成的任务,请改为调用 invalidateAndCancel。

关于ios - NSURLSessionDataTask 超时后续请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31427934/

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