判断网络是否连接的几种方法

时间:2021-01-29 19:34:14

第一种方法:
需要使用Reachability第三方库

- (void)checkInternetConnection
{
internetReachableFoo = [Reachability reachabilityWithHostname:@"www.baidu.com"];
// Internet is reachable
internetReachableFoo.reachableBlock = ^(Reachability*reach){
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
//有网络连接
NSLog(@"thi net is connected!");
});
};
// Internet is not reachable
internetReachableFoo.unreachableBlock = ^(Reachability*reach){
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
//无网络连接
NSLog(@"thi net is disconnected");
});
};
[internetReachableFoo startNotifier];
}

第二种方法:
这种方法需要导入以下系统库

#include <netdb.h>
#import <SystemConfiguration/SystemConfiguration.h>
/**
* 网络是否连通。
*
* @return 网络状态枚举值
* @retval YES 网络通畅
* @retval NO 网络不通
*/

- (BOOL)isConnectedToNetwork
{
// Create zero addy
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;

// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;

BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);

if (!didRetrieveFlags){
printf("Error. Could not recover network reachability flags\n");
return NO;
}

BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
return (isReachable && !needsConnection) ? YES : NO;
}

第三种方法:

//第三种方法
- (BOOL)connected
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return networkStatus != NotReachable;
}

第四种方法:

-(BOOL)newtworkType
{
NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"]subviews];
NSNumber *dataNetworkItemView = nil;

for (id subview in subviews) {
if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
dataNetworkItemView = subview;
break;
}
}
switch ([[dataNetworkItemView valueForKey:@"dataNetworkType"]integerValue]) {
case 0:
NSLog(@"No wifi or cellular");
return NO;
break;
case 1:
NSLog(@"2G");
return YES;
break;
case 2:
NSLog(@"3G");
return YES;
break;
case 3:
NSLog(@"4G");
return YES;
break;
case 4:
NSLog(@"LTE");
return YES;
break;
case 5:
NSLog(@"Wifi");
return YES;
break;
default:
break;
}
return NO;
}