Search code examples
objective-cxcodereachability

How to check network status in iphone app?


I have setup some methods to check network status in my app.

In my viewDidLoad method I call initNetworkCheck:

[self initNetworkCheck];
[super viewDidLoad];
if(internetActive == NO){     
    compose.enabled = NO;
}

So I want to check on startup if the hardware has internet connection. The problem is it gives me always NO but internetActive is actually YES when I log it.

//[[[[[[network check methods
-(void)checkNetworkStatus:(NSNotification *)notice{
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus) {
        case NotReachable:{
            self.internetActive = NO; 
            break;
        }
        case ReachableViaWiFi:{
            self.internetActive = YES;
            break;
        }
        case ReachableViaWWAN:{
            self.internetActive = YES;
            break;
        }
    }
    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus){
        case NotReachable:{
            self.hostActive = NO;
            break;
        }
        case ReachableViaWiFi:{
            self.hostActive = YES;
            break;
        }
        case ReachableViaWWAN:{
            self.hostActive = YES;
            break;
        }
    }

}
-(void)initNetworkCheck{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

    internetReachable = [[Reachability reachabilityForInternetConnection] retain];
    [internetReachable startNotifier];

    hostReachable = [[Reachability reachabilityWithHostName:@"www.google.com"] retain];
    [hostReachable startNotifier];
}
//]]]]]]

Any ideas?


Solution

  • I suggest to make use of Apple's Reachability class. Here is a sample App by Apple.

    The Reachability sample application demonstrates how to use the SystemConfiguration framework to monitor the network state of an iPhone or iPod touch. In particular, it demonstrates how to know when IP can be routed and when traffic will be routed through a Wireless Wide Area Network (WWAN) interface such as EDGE or 3G.