ios – NSURLSessionDataTask超时后续请求失败

ios – NSURLSessionDataTask超时后续请求失败,第1张

概述我正在创建一个NSMutableRequest: self.req = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0]; 超时设置为10秒,因为我不希望用户等待太久才能得到反馈. 之后,我创建一个NSURLSessionDa 我正在创建一个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,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

并通过以下方式使会话无效:

[[NSURLSession sharedSession]invalIDateAndCancel];

从苹果的文档:

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超时后续请求失败全部内容,希望文章能够帮你解决ios – NSURLSessionDataTask超时后续请求失败所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1096206.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存