0

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?

4
  • You can check currentReachabilityStatus property any time without starting monitoring. Commented Jul 2, 2014 at 16:07
  • 1
    stackoverflow.com/a/9358166/158983 Commented Jul 2, 2014 at 16:12
  • Be careful about blocking the thread in applicationDidFinishLaunchingWithOptions. If you block it for too long the app will automatically close. Commented Jul 2, 2014 at 17:24
  • @LyricalPanda thanks for your advice and sorry for such poor example :) Just focus on the question Commented Jul 2, 2014 at 17:42

1 Answer 1

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.