Search code examples
iosconnectionafnetworkingreachability

How to check for internet connection synchronously?


How to check for network synchronously? I want the network checking to block the calling thread and return the correct result

I tried tonymillion's Reachability and AFNetworkReachabilityManager but they all use callback block. It means the reachability status is unknown before the callback.

I want to check network at applicationDidFinishLaunchingWithOptions: but at this point, reachability is AFNetworkReachabilityStatusUnknown (AFNetworkReachabilityManager) or not reliable (tonymillion's Reachability)

I see that the only way is to perform NSURLConnection against some host (google.com for example) like this Check for internet connection - iOS SDK

Are there any better way?


Solution

  • To answer my own question: It is reliable

    Read this Technical Q&A QA1693 Synchronous Networking On The Main Thread

    reachability — The System Configuration framework reachability API () operates synchronously by default. Thus, seemingly innocuous routines like SCNetworkReachabilityGetFlags can get you killed by the watchdog. If you're using the reachability API, you should use it asynchronously. This involves using the SCNetworkReachabilityScheduleWithRunLoop routine to schedule your reachability queries on the run loop

    So we can use it like this iOS: Check whether internet connection is available

    - (BOOL) isConnectionAvailable
    {
        SCNetworkReachabilityFlags flags;
            BOOL receivedFlags;
    
            SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(CFAllocatorGetDefault(), [@"dipinkrishna.com" UTF8String]);
            receivedFlags = SCNetworkReachabilityGetFlags(reachability, &flags);
            CFRelease(reachability);
    
            if (!receivedFlags || (flags == 0) )
            {
                return FALSE;
            } else {
            return TRUE;
        }
    }