views:

354

answers:

2

I am having a problem with a network request that should timeout, but the method is not called. The request is as follows:

#define kCONNECT_TIMEOUT 20.0

request = [NSMutableURLRequest requestWithURL: aUrl];
[request setHTTPMethod: @"POST"];
postData = [jsonData dataUsingEncoding:NSASCIIStringEncoding];
[request setHTTPBody:postData];
[request setValue:@"text/xml" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request setCachePolicy:NSURLCacheStorageAllowed];
[request setTimeoutInterval:kCONNECT_TIMEOUT];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
assert(self.connection != nil);

This should get a callback to

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)_error 

But after 4 minutes no error message is displayed. Anyone know why this might be?

A: 

If you want better timeout management on http requests using NSURLConnection then it is much better to run the request asynchronous together with an NSTimer that can cancel the NSURLConnection when it fires because the timeout period expired.

This also means you don't have to deal with threads, which is generally a good idea. Async event (runloop) based operations are the way to go in 99.9% of the cases on the iPhone.

St3fan
I thought the above code was asynchronous, is it not? So what you are saying is that request setTimeoutInterval is broken and better to explicitly define a separate timer instead?
Sorry you are right. Your code is async. But yes, the same applies .. if you want better control over the timeout then simply run a timer next to the request.
St3fan
I recently did a demo app and there was no internet connection and I noticed that yes it did time out as it should. This is using iOS 4, so perhaps this issue is fixed now.
A: 

A representative from Apple has divulged that SDK 3.0 and later enforce a minimum timeout of (you guessed it) four minutes:

https://devforums.apple.com/thread/25282

If you try to set a timeout value of less than 240 seconds, it gets clamped up to 240. If you need a shorter timeout, I cast my vote for St3fan's solution.

Tom
No sh*t Sherlock! You're right. A timer it is then.
Got it all working perfectly now. Thanks for the comments.