Avoiding the 30 second tcp timeout on iPhone OS

So you are writing the next great iPhone app and you pull some data from a server using TCP, but what happens in the unhappy scenario?

TCP timeout takes about 30 seconds, if in the main loop, your app freezes, in a separate thread it is at best annoying. Here is a little work around using the SystemConfiguration network to check if the LAN/WAN is up, and a NSURL to check if we can actually reach a page.

- (BOOL)isHostAvailable:(NSString*)hostName {

// this should check the host but does not work in the simulator, aka it returns YES when should be no
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName cStringUsingEncoding:NSASCIIStringEncoding]);
SCNetworkReachabilityFlags flags;
BOOL success = SCNetworkReachabilityGetFlags(reachability, &flags);
if (reachability) {

if ( ( success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired) ) == NO) {
return NO;

// we know at least the network is up, second check for a known page
NSData *dataReply;
NSURLResponse *response;
NSError *error;

// create the request
NSString *urlString = [NSString stringWithFormat:@"http://%@/hapi/index.php", hostName];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]
// Make the connection
dataReply = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];

if (response != nil) {
NSLog(@"SNNetworkController.isHostAvailable %@", response);
return YES;
} else {
// inform the user that the download could not be made
NSLog(@"SNNetworkController.isHostAvailable %@ %@", response, error);
return NO;

Tagged with: , ,
Posted in Code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: