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.