ios 测试网络是否连接
转自:http://blog.csdn.net/lwq421336220/article/details/16982857
- (BOOL) connectedToNetwork
{
//创建零地址,0.0.0.0的地址表示查询本机的网络连接状态
structsockaddr_in zeroAddress;
bzero(&zeroAddress,sizeof(zeroAddress));
zeroAddress.sin_len =sizeof(zeroAddress);
zeroAddress.sin_family =AF_INET;
SCNetworkReachabilityRef defaultRouteReachability =SCNetworkReachabilityCreateWithAddress(NULL, (structsockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags =SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags)
{
printf("Error. Could not recover network reachability flagsn");
returnNO;
}
BOOL isReachable = ((flags &kSCNetworkFlagsReachable) != 0);
BOOL needsConnection = ((flags &kSCNetworkFlagsConnectionRequired) != 0);
return (isReachable && !needsConnection) ?YES : NO;
}
使用的时候:
if ([selfconnectedToNetwork]) {
}else{
UIAlertView *alert=[[UIAlertViewalloc]initWithTitle:@"提示" message:@"网络连接失败,请查看网络连接。" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil,nil];
[alertshow];
}