我在viewController.m类中有以下代码:
- (void) testInternetConnection
{
internetConnection = [Reachability reachabilityWithHostname:@"www.google.com"];
// Internet is reachable
internetConnection.reachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Yayyy, we have the interwebs!");
});
};
// Internet is not reachable
internetConnection.unreachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Someone broke the internet :(");
});
};
[internetConnection startNotifier];
}
我用它来测试状态:
BOOL status = ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
答案 0 :(得分:2)
startNotifier意味着任何网络状态更改后都会通知谁注册了kReachabilityChangedNotification通知。
您不必将其放在每个视图控制器中。
1,您需要一个单例实例并且具有用于保持网络状态的成员值。
2,注册kReachabilityChangedNotification通知,处理它并获取网络状态并将其存储在您的成员值和发布通知(自定义通知)中以通知其他人(您的viewcontroller)。
3,提供接口以获取当前网络状态,以便视图控制器在网络状态发生变化时知道网络状态。
答案 1 :(得分:0)
在您的app delegate类中尝试此操作。
在应用程序didFinishLaunchingWithOptions中编写此代码。
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
Reachability *hostReachable = [[Reachability reachabilityWithHostName: @"www.google.com"] retain];
[hostReachable startNotifier];
在Appdelegate类中编写此方法。
- (void) reachabilityChanged: (NSNotification* )note
{
Reachability* curReach = [note object];
[self updateInterfaceWithReachability: curReach];
}
- (void) updateInterfaceWithReachability: (Reachability*) curReach
{
if(curReach == hostReachable)
{
NetworkStatus netStatus = [curReach currentReachabilityStatus];
if (netStatus == 0 )
{
NSLog(@"offline");
}
else
{
NSLog(@"online");
}
}
}