Search code examples
objective-cnsurlconnection

Quick detecting, if server is offline


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.


Solution

  • 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];
    }