How to verify network connectivity in objective-c

旧时模样 提交于 2019-12-20 09:32:36

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/5008534/how-to-verify-network-connectivity-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!