Testing a Network Connection on the iPhone

If your iPhone app needs to test for a network connection, try this code out:

#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>

+ (BOOL) connectedToNetwork
{
	// Create zero addy
	struct sockaddr_in zeroAddress;
	bzero(&zeroAddress, sizeof(zeroAddress) ) ;
	zeroAddress. sin_len = sizeof(zeroAddress) ;
	zeroAddress. sin_family = AF_INET;
	// Recover reachability flags
	SCNetworkReachabilityRef defaultRouteReachability =
	SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*) &zeroAddress) ;
	SCNetworkReachabilityFlags flags;
	BOOL didRetrieveFlags =
	SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) ;
	CFRelease(defaultRouteReachability) ;
	if (!didRetrieveFlags)
	{
		printf(" Error. Could not recover network reachability flags\n") ;
		return 0;
	}
	BOOL isReachable = flags & kSCNetworkFlagsReachable;
	BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
	return (isReachable && !needsConnection) ? YES : NO;
}
Source: Sadun, E. (2009). The Iphone developer’s cookbook : building mobile applications with the iphone sdk. Crawfordsville, IN: Pearson Education.
Advertisements
Testing a Network Connection on the iPhone

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