Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Darkroom

Guest
Original poster
Dec 15, 2006
2,445
0
Montréal, Canada
i don't have access to an iPhone for testing (only an iPod touch). i've read some forum posts claiming that the code listed below will only work with wifi, and not a cellular connection. is this true?

Code:
- (BOOL)internetConnection
	{
	//INTERNET CONNECTION TESTING
	//Add the SystemConfiguration framework 
	//#import <SystemConfiguration/SCNetworkReachability.h>
	//#import <netinet/in.h>
	
	struct sockaddr_in zeroAddress;
	bzero(&zeroAddress, sizeof(zeroAddress));
	zeroAddress.sin_len = sizeof(zeroAddress);
	zeroAddress.sin_family = AF_INET;

	SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
	SCNetworkReachabilityFlags flags;

	BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
	CFRelease(defaultRouteReachability);

	if (!didRetrieveFlags)
		return 0;

	BOOL isReachable = flags & kSCNetworkFlagsReachable;
	BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
	
	return (isReachable && !needsConnection) ? YES : NO;
	}

- (IBAction)gotoAppStore
	{
	if ([self internetConnection] == YES)
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=kAppId"]];
		else
		{
		UIAlertView *alert = [[UIAlertView alloc]	initWithTitle:nil
									message:NSLocalizedString(SMConstNoInternetConnectionAlertMessage, nil) 
									delegate:self
									cancelButtonTitle:@"OK"
									otherButtonTitles:nil];
		[alert show];
		[alert release];
		}
	}
 
There are several better options than what you are doing.

I personally just use something like this:

Code:
-(BOOL)connectedToInternet
{
	return ([NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"] encoding:NSUTF8StringEncoding error:NULL]!=NULL)?YES:NO;
}

It's not the most sophisticated, but for my particular need, it works fine.

For a more complex solution, look at Apple's Reachability sample code.
 
Darkroom,

I'm pretty sure the code you show should work on the cell network as well as WiFi, but I'm not absolutely sure.

I am absolutely sure that it's not the best way and not the recommended way to do this. Look at the Reachability sample code. It works asynchronously, which I guess is a little less convenient for the kind of code that you show but it's probably better.

Don't do a synchronous network check because it can cause your app to crash.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.