Skip to content

Function to test internet connection easily:

Vladde Nordholm edited this page Jul 18, 2018 · 2 revisions

I created easy function to test internet connection. Add it in AppUtility class.

static dispatch_queue_t networkQueue;

+(void)isNetworkAvailableWithBlock:(void (^)(BOOL wasSuccessful))completion{
 
    static dispatch_once_t queueCreationGuard;

    dispatch_once(&queueCreationGuard, ^{
        networkQueue = dispatch_queue_create("NetworkQueue", NULL);
    });

    __block Reachability* reach;

    dispatch_async(networkQueue, ^{
        reach = [Reachability reachabilityWithHostname:@"www.google.com"];
        reach.reachableBlock = ^(Reachability *reach){
            [reach stopNotifier];
            completion(true);
        };
    
        reach.unreachableBlock = ^(Reachability *reach){
            [reach stopNotifier];
            completion(false);
        };
        [reach startNotifier];
    });
}

Happy Programming!!! 👍


Another, simpler, method to test internet connection:

+ (BOOL)hasInternetConnection {
    return [[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable;
}
Clone this wiki locally