How do I check internet connection in an OS X cocoa application? Can Apple's iOS Reachability example code be reused for this purpose?
Thanks,
Nava
How do I check internet connection in an OS X cocoa application? Can Apple's iOS Reachability example code be reused for this purpose?
Thanks,
Nava
The current version of Reachability code (2.2) listed on Apple's site and referenced above does NOT compile as-is for a Mac OS X Cocoa application. The constant kSCNetworkReachabilityFlagsIsWWAN is only available when compiling for TARGET_OS_IPHONE and Reachability.m references that constant. You will need to #ifdef the two locations in Reachability.m that reference it like below:
#if TARGET_OS_IPHONE
(flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',
#else
0,
#endif
and
#if TARGET_OS_IPHONE
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
// ... but WWAN connections are OK if the calling application
// is using the CFNetwork (CFSocketStream?) APIs.
retVal = ReachableViaWWAN;
}
#endif
This code will help you to find if internet is reachable or not:
-(BOOL)isInternetAvail
{
BOOL bRet = FALSE;
const char *hostName = [@"google.com" cStringUsingEncoding:NSASCIIStringEncoding];
SCNetworkConnectionFlags flags = 0;
if (SCNetworkCheckReachabilityByName(hostName, &flags) && flags > 0)
{
if (flags == kSCNetworkFlagsReachable)
{
bRet = TRUE;
}
else
{
}
}
else
{
}
return bRet;
}
For more information you can look at the iphone-reachability
Unicorn's solution is deprecated, but you can get equivalent results using the following code:
SCNetworkReachabilityRef target;
SCNetworkConnectionFlags flags = 0;
Boolean ok;
target = SCNetworkReachabilityCreateWithName(NULL, hostName);
ok = SCNetworkReachabilityGetFlags(target, &flags);
CFRelease(target);
Apple has a nice code which does it for you. You can check if your connection is WiFi for instnace or just cell/WiFi. link text
I know this is an old thread but for anyone running into this in 2018, there's an simpler and quicker solution using a Process
and the ping
command.
Swift 4 example:
func ping(_ host: String) -> Int32 {
let process = Process.launchedProcess(launchPath: "/sbin/ping", arguments: ["-c1", host])
process.waitUntilExit()
return process.terminationStatus
}
let internetAvailable = ping("google.com") == 0
print("internetAvailable \(internetAvailable)")