Reachability(判断网络是否连接)
2013-01-24 09:36 三戒1993 阅读(115) 评论(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:@"连接失败"]; } }