JimmyBond
JimmyBond

Reputation: 95

How to verify network connectivity in objective-c

I was looking over the Reachability sample project on developer.apple.com and found that it was a large project just to verify you had network connectivity.

First part of the question is "What is the minimum code required to find out if the device can reach a 3G or wifi network?"

And next should this be done inside the appDelegate (on start) or inside the first View Controller that is launched?

Thank you in advance

Upvotes: 6

Views: 2517

Answers (1)

zrzka
zrzka

Reputation: 21219

It's not large, it really does what you want. If it is too big for you, you can extract what you need only like reachabilityForLocalWiFi. But I'm afraid that it will not be much smaller.

Yes, you can use reachability in your application delegate or inside the first view controller.

Reachability notification registration ...

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(networkReachabilityDidChange:)
                                             name:kReachabilityChangedNotification
                                           object:nil];
__reachability = [[Reachability reachabilityWithHostName:@"www.google.com"] retain];
[__reachability startNotifier];

... callback method example ...

- (void)networkReachabilityDidChange:(NSNotification *)notification {
  Reachability *reachability = ( Reachability * )[notification object];
  if ( reachability.currentReachabilityStatus != NotReachable ) {
    // Network is available, ie. www.google.com
  } else {
    // Network is not available, ie. www.google.com
  }
}

... do not forget to stop notifications, remove observer and release rechability object.

Upvotes: 3

Related Questions