微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – NSURLSessionDataTask超时后续请求失败

我正在创建一个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.

原文地址:https://www.jb51.cc/iOS/329613.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐