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
5 Answers 5
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
1 Comment
'-',
, not 0,
above.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);
2 Comments
(flags & kSCNetworkReachabilityFlagsIsDirect)
. For a plugged-in Internet connection, check if (flags & kSCNetworkReachabilityFlagsIsLocalAddress)
. Also, when there is no connection at all, the flags for kSCNetworkReachabilityFlagsTransientConnection
and kSCNetworkReachabilityFlagsConnectionRequired
show up.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
3 Comments
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)")
WebView
'sframeLoadDelegate
, it'll receive when aprovisionalLoadError
occurs, which is pretty much immediate if there's no web connection. Since I'm using aWebView
(from theWebKit.framework
) anyways, I'm just throwing up an error message as soon as it gets theprovisionalLoadError
.