今天写了两个检测网络状态的方法
第一个:
使用这种方法时一定要保证statusbar没有隐藏。如果你的App隐藏了statusbar,那么你也就不能通过这种方法获得网络状态。
+ (NSString *)networkingStatesFromStatebar {
// 状态栏是由当前app控制的,首先获取当前app
UIApplication *app = [UIApplication sharedApplication];
NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
int type = 0;
for (id child in children) {
if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
}
}
NSString *stateString = @"wifi";
switch (type) {
case 0:
stateString = @"notReachable"; // 没有网络
NSLog(@"%@", stateString);
break;
case 1:
stateString = @"2G";
NSLog(@"%@", stateString);
break;
case 2:
stateString = @"3G";NSLog(@"%@", stateString);
break;
case 3:
stateString = @"4G";NSLog(@"%@", stateString);
break;
case 4:
stateString = @"LTE"; // 比4G更快的蜂窝网
NSLog(@"%@", stateString);
break;
case 5:
stateString = @"wifi";
NSLog(@"%@", stateString);
break;
}
return stateString;
}
#import "AFNetworking.h"
@property (nonatomic, copy) NSString *status;
- (void)AFNetWorkingStatus
{
/**
AFNetworkReachabilityStatusUnknown = -1, // 未知
AFNetworkReachabilityStatusNotReachable = 0, // 无连接
AFNetworkReachabilityStatusReachableViaWWAN = 1, // 3G 花钱
AFNetworkReachabilityStatusReachableViaWiFi = 2, // WiFi
*/
// 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
// 检测网络连接的单例,网络变化时的回调方法
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
if (status == -1) {
//未知
self.status = @"您目前网络状态为:未知,请小心";
[self showalt];
} else if (status == 0) {
//无连接
self.status = @"您目前网络状态为:无连接";
[self showalt];
} else if (status == 1) {
//3g网络
self.status = @"您目前网络状态为供应商网络,请注意流量";
[self showalt];
} else if (status == 2) {
//wifi连接
self.status = @"您目前网络状态为:wifi,请放心浏览";
[self showalt];
}
}];
}
- (void)showalt
{
UIAlertController *al = [UIAlertController alertControllerWithTitle:@"提示" message:self.status preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:nil];
[al addAction:cancel];
[self presentViewController:al animated:YES completion:nil];
}