我正在创建一个 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];
}
self.req
。不过我不太确定。 - Mrunal