首页 > 其他 > 详细

Reachability(判断网络是否连接)

时间:2015-10-13 22:45:29      阅读:198      评论:0      收藏:0      [点我收藏+]
类似于一个网络状况的探针。
  [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
    
    hostReach = [[Reachability reachabilityWithHostName: @"hubj.cnblogs.com"] retain];
    [hostReach startNotifier];
    
    wifiReach=[[Reachability reachabilityForLocalWiFi]retain];
    [wifiReach startNotifier];
 
- (void)reachabilityChanged: (NSNotification* )note {
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    
    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    
    switch (netStatus)
    {
        case NotReachable:
        {
            NSLog(@"Access Not Available");
            break;
        }
            
        case ReachableViaWWAN:
        {
            NSLog(@"Reachable WWAN");
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"Reachable WiFi");
            break;
        }
    }

}
 
判断网络是否连接
/***
* 此函数用来判断是否网络连接服务器正常
* 需要导入Reachability类
*/
+ (BOOL)isExistenceNetwork
{
    BOOL isExistenceNetwork;
    Reachability *reachability = [Reachability reachabilityWithHostName:@""];  // 测试服务器状态
    
     switch([reachability currentReachabilityStatus]) {
            case NotReachable:
                  isExistenceNetwork = FALSE;
                  break;
             case ReachableViaWWAN:
                   isExistenceNetwork = TRUE;
                   break;
              case ReachableViaWiFi:
                    isExistenceNetwork = TRUE;
                    break;
     }
     return  isExistenceNetwork;
}
 
实时通知网络状况
/*
* 在应用委托的方法didFinishLaunchingWithOptions中添加
*/

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
reachability = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
[reachability startNotifier];
........
return YES;

/**
*此函数通过判断联网方式,通知给用户
*/
- (void)reachabilityChanged:(NSNotification *)notification
{
      Reachability *curReachability = [notification object];
      NSParameterAssert([curReachability isKindOfClass:[Reachability class]]);
      NetworkStatus curStatus = [curReachability currentReachabilityStatus];
      if(curStatus == NotReachable) {
          [DOIN_Util logFax:@"连接失败"];
      }
}

 

Reachability(判断网络是否连接)

原文:http://www.cnblogs.com/langtianya/p/4876014.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!