I am creating a NSMutableRequest
:
self.req = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
The timeout is set to be 10 seconds because I don't want the user to wait too long to get a feedback.
After that I create a 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];
}
The problem is the server goes into Gateway Timeout and it takes a lot of time. I get the timeout error and I give a feedback to the user, but all the following API calls fail in the same way due to timeout error. The only way to stop it is to kill the app and start over. Is there something I should do to kill the task or the connection after a timeout error? If I don't set a timeout and I wait until I receive the error code from the server all the following calls work perfectly (But the user waits a lot!).
I tried to cancel the task:
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
if there is an error/timeout. Not sure about this though. – Ganges