Reputation: 2585
We use a PHP server and an iOS app.
I use NSURLConnection
to send a message to the server. If server is unavailable, e.g. the address is incorrect then we wait for an error after 60–90 secs. This is a long time.
How do I decrease this time? Is there any quick function to check for server availability?
If I first call
[request setTimeoutInterval:10];
[request setHTTPBody:[message data]];
when I check [request timeoutInterval] it is still 240, not 10. So interesting..
If I add a setTimeoutInterval:
call before the connection is created like so:
[request setTimeoutInterval:10];
connection = [[NSURLConnection alloc] initWithRequest: request delegate: self];
The request still returns after a long time.
Upvotes: 0
Views: 1618
Reputation: 8057
This Delegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
if (error.code == NSURLErrorTimedOut)
Upvotes: 0
Reputation: 1465
If the Server really is down, you could always first check with the reachabillity Framework and check if the server can be reached, before you fire your HTTP request.
See this answer for a sample of this:
Upvotes: 1
Reputation: 7522
Yeah, timeouts don't quite work like you would expect. One solution is to set up a timer that cancels the connection after your desired interval has elapsed. I did this in my ReallyRandom class, and it seems to do the trick.
It looks something like this:
connection = [[NSURLConnection alloc] initWithRequest: request delegate: self startImmediately:NO];
timer = [NSTimer scheduledTimerWithTimeInterval:10
target:self
selector:@selector(onTimeExpired)
userInfo:nil
repeats:NO];
[connection start];
// When time expires, cancel the connection
-(void)onTimeExpired
{
[self.connection cancel];
}
Upvotes: 1
Reputation: 8163
You can reduce the timeout time in the request, specifying the timeoutInterval
parameter in the method:
+ (id)requestWithURL:(NSURL *)theURL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval
But it's difficult to tell whether the server is unavailable or just busy. You can just decide that if the server does not respond in a certain interval, it is likely that it is down. Otherwise you will have to wait.
Upvotes: 0