Search code examples
iosobjective-cnetwork-programmingreachability

Which is the best method to check the network reachability in objective c


I'm new to objective c. I found a lot of method for checking the internet connectivity like reachability test, using AF Networking etc.Which is the best method?Any help?


Solution

  • I always prefer to use Reachability https://github.com/tonymillion/Reachability like below. Description on GitHub is so clear for why you should use it -> "This is a drop-in replacement for Apple's Reachability class. It is ARC-compatible, and it uses the new GCD methods to notify of network interface changes".

    Reachability *internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];
    
    // Internet is reachable
    internetReachableFoo.reachableBlock = ^(Reachability*reach)
    {
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
    
            //do something
            NSLog(@"REACHABLE!");
    
            } error:^(NSError * _Nullable error) {
                NSLog(@"Error:%@ ", [error localizedDescription]);
            }];
        });
    };
    
    // Internet is not reachable
    internetReachableFoo.unreachableBlock = ^(Reachability*reach)
    {
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
    
            //do something
            NSLog(@"UNREACHABLE!");
    
            });
    };
    
    [internetReachableFoo startNotifier];
    

    goodluck :)