Swift
// MARK: // MARK: 判断有无网络 /// 判断有无网络 func stringIsHaveNetworking() -> String? { // 状态栏是由当前app控制的,首先获取当前app let app = UIApplication.sharedApplication(); let childrenArray = app.valueForKeyPath("statusBar")?.valueForKeyPath("foregroundView")?.subviews; var type = 0; for i in childrenArray ?? [] { // 判断 类型 if i.isKindOfClass(NSClassFromString("UIStatusBarDataNetworkItemView")!) { type = (i.valueForKeyPath("dataNetworkType")?.integerValue)!; } } switch type { case 1: return "2G"; case 2: return "3G"; case 3: return "4G"; case 5: return "WIFI"; default: return nil; } }
OC
- (NSString *)stringIsHaveNetworking { // 状态栏是由当前app控制的,首先获取当前app // 拿到 AppDelegate 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")]) { type = [[child valueForKeyPath:@"dataNetworkType"] intValue]; } } switch (type) { case 1: return @"2G"; break; case 2: return @"3G"; case 3: return @"4G"; case 5: return @"WIFI"; default: return @"NO-WIFI";//代表未知网络 break; }}
学自:http://www.jianshu.com/p/b643bf74b8c6