使用 Apple 的默认可达性类:
从此链接下载可达性项目
将 Reachability.h 和 Reachability.m 文件复制到您的项目中。
并在应用程序委托文件中设置此方法。
-(void)initializeRechabilityObeserver
{
//Change the host name here to change the server your monitoring
hostReach = [Reachability reachabilityWithHostName: @"www.apple.com <http://www.apple.com>"];
[hostReach startNotifier];
//[self updateInterfaceWithReachability: hostReach];
internetReach = [Reachability reachabilityForInternetConnection];
[internetReach startNotifier];
//[self updateInterfaceWithReachability: internetReach];
wifiReach = [Reachability reachabilityForLocalWiFi] ;
[wifiReach startNotifier];
//[self updateInterfaceWithReachability: wifiReach];
}
要获取可达性更改通知,请使用以下代码:
在 Application didFinishLaunching 中添加这个通知方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
internetReachable = [Reachability reachabilityForInternetConnection] ;
[internetReachable startNotifier];
}
并添加此方法:
- (void)reachabilityChanged: (NSNotification* )note
{
NSLog(@"Reachability changed");
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
[self updateInterfaceWithReachability: curReach];
}