2013-12-11 43 views
0

状态我在viewController.m类下面的代码:可达性和IOS

 - (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]; 
} 
  1. 如何使用startNotifier?
  2. 我是否必须将这个放在每个视图控制器中,我想测试互联网连接?

我用这个来测试状态:

BOOL status = ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable); 

回答

2

startNotifier改变会通知谁注册kReachabilityChangedNotification通知任何网络状态之后表示。

你不必把它放在每个视图控制器中。

1,您需要一个单例实例并具有用于保持网络状态的成员值。

2,注册kReachabilityChangedNotification通知,处理它并获取网络状态并将其存储在您的成员值和Post Notification(自定义通知)中以通知其他人(您的viewcontroller)。

3,提供接口获取当前网络状态,以便您的视图控制器在网络状态发生变化时知道网络状态。

0

在您的应用程序委托类中尝试此操作。

在应用程序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"); 
       } 
     } 
    }