1.系统自带的
+(BOOL)connectedNetWork
{
//创建零地址,0.0.0.0的地址表示查询本机的网络连接状态
struct sockaddr_storage zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.ss_len =sizeof(zeroAddress);
zeroAddress.ss_family =AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability =SCNetworkReachabilityCreateWithAddress(NULL, (structsockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
//获得连接的标志
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
//如果不能获取连接标志,则不能连接网络,直接返回
if (!didRetrieveFlags)
{
return NO;
}
//根据获得的连接标志进行判断
BOOL isReachable = flags & kSCNetworkFlagsReachable; //是否已经链接
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; //是否需要连接
return (isReachable&&!needsConnection) ? YES : NO;
}
2.Reachability(第三方)
1.类方法创建
{
Reachability *rea;
}
2。进行判断
-(void)btnAction
{
rea=[Reachability reachabilityWithHostName:@"www.baidu.com"];
switch ([rea currentReachabilityStatus]) {
case ReachableViaWiFi:
NSLog(@"wifi");
break;
case ReachableViaWWAN:
NSLog(@"3G");
break;
case NotReachable:
NSLog(@"NotReachable");
break;
default:
break;
}
//一直判断网络状态变化的结果,需要真机测试
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(netWorkClick) name:kReachabilityChangedNotification object:nil];
}
-(void)netWorkClick{
NSLog(@"网络状态有变化");
//判断网络状态
switch ([rea currentReachabilityStatus]) {
case ReachableViaWiFi:
NSLog(@"wifi");
break;
case ReachableViaWWAN:
NSLog(@"3G");
break;
case NotReachable:
NSLog(@"没有网络");
default:
break;
}
}