check internet connection in cocoa application

后端 未结 5 672
情深已故
情深已故 2020-11-30 09:06

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条回答
  • 2020-11-30 09:39

    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
    
    0 讨论(0)
  • 2020-11-30 09:48

    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

    0 讨论(0)
  • 2020-11-30 09:52

    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);
    
    0 讨论(0)
  • 2020-11-30 09:52

    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

    0 讨论(0)
  • 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)")
    
    0 讨论(0)
提交回复
热议问题