如何验证objective-c中的网络连接 [英] How to verify network connectivity in objective-c

查看:125
本文介绍了如何验证objective-c中的网络连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看developer.apple.com上的Reachability示例项目,发现这是一个大型项目,只是为了验证您是否有网络连接。

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.

第一部分问题是找出设备是否可以到达3G或wifi网络所需的最低代码是多少?

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?"

接下来应该在appDelegate内完成(在开始时)或在第一个启动的View Controller内部?

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

提前谢谢

推荐答案

它不大,它真的做你想要的。如果它对你来说太大了,你可以只提取你需要的东西,比如reachabilityForLocalWiFi。但我担心它不会小得多。

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.

这篇关于如何验证objective-c中的网络连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆