iOS获取手机当前的网络状态

时间:2023-03-09 00:53:43
iOS获取手机当前的网络状态

获取iOS网络状态,目前有两个办法。

1.通过监听手机状态栏的信息。

2.通过使用官方提供的类Reachability。

一、通过手机监听手机状态栏的信息

好处:

1.可以通过苹果的审核上架AppStore。

2.代码量少,简单易懂。

3.可以区分网络类型,精确到2G,3G,4G。

缺点:必须保证在使用该方法的过程中,手机状态栏statusBar没有隐藏。

代码如下:

- (NSString *)networkingStatesFromStatusBar {
UIApplication *app = [UIApplication sharedApplication];
NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
int type = ;
for (id child in children) {
if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
}
}
NSString *networkStateString = @"wifi";
switch (type) {
case :
networkStateString = @"notReachable";
break;
case :
networkStateString = @"2G";
break;
case :
networkStateString = @"3G";
break;
case :
networkStateString = @"4G";
break;
case :
stateString = @"LTE";
break;
case :
networkStateString = @"wifi";
break;
default:
break;
}
return networkStateString;
}

二、通过通过使用官方提供的类Reachability

好处:官方提供的权威方法。无需依赖状态栏。

缺点:只有三种网络状态

typedef NS_ENUM(NSInteger, NetworkStatus) {
// Apple NetworkStatus Compatible Names.
NotReachable = ,
ReachableViaWiFi = ,
ReachableViaWWAN =
};

使用:

1.下载并导入Reachability,链接:https://github.com/tonymillion/Reachability

2.导入SystemConfiguration.framework框架

3.代码实现:

Reachability提供了两种实现方法:

1.使用Block回调,代码如下

    /** 网络状态对象*/
Reachability *reach= [Reachability reachabilityWithHostName:@"www.apple.com"];
//使用block回调实现
reach.reachableBlock = ^(Reachability *reach) {
dispatch_async(dispatch_get_main_queue(), ^{
NetworkStatus netStatus = [reach currentReachabilityStatus];
switch (netStatus) {
case NotReachable:
NSLog(@"未检测到网络");
break;
case ReachableViaWiFi:
NSLog(@"wifi");
break;
case ReachableViaWWAN:
NSLog(@"蜂窝网络");
break;
default:
break;
}
});
};
reach.unreachableBlock = ^(Reachability *reach) {
NSLog(@"UNREACHBLE!");
};
[reach startNotifier];

2.使用通知,代码如下

    /** 网络状态对象*/
Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
[reach startNotifier];

监听方法的实现

-(void)reachabilityChanged:(NSNotification *)notification {
Reachability *curReach = [notification object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
NetworkStatus netStatus = [curReach currentReachabilityStatus];
switch (netStatus) {
case NotReachable:
NSLog(@"未检测到网络");
break;
case ReachableViaWiFi:
NSLog(@"wifi");
break;
case ReachableViaWWAN:
NSLog(@"蜂窝网络");
break;
default:
break;
}
}

最后不要忘记移除通知。

- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}