获取网络状态的方法有两种。这是我觉得比较方便的一种。还有一种是结合RunLoop去做的,不过那种要导入其他头文件。用起来也是一样。
//
// ViewController.m
// Runtime获取当前网络状态
//
// Created by 陆巧怡 on 15/8/4.
// Copyright (c) 2015年 Simon. All rights reserved.
//
#import "ViewController.h"
#import <objc/message.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self takeOutThestatusBar];
}
#pragma 找到状态栏
-(void)findStatusBar{
//获取当前的app
UIApplication *app = [UIApplication sharedApplication];
//遍历当前app的所有属性 找到关于状态栏的属性
unsigned int outCount = 0;
Ivar *ivars = class_copyIvarList([app class], &outCount);
for (int i =0; i<outCount; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
NSString *propertyName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
if ([propertyName isEqualToString:@"_statusBar"]) {
NSLog(@"状态栏");
}
}
}
#pragma 通过KVC找出状态栏
-(void)takeOutThestatusBar{
//获取当前的app
UIApplication *app = [UIApplication sharedApplication];
//通过KVC获取到当前APP的状态栏
id statusBar = [app valueForKey:@"statusBar"];
NSArray *childensArray = [[statusBar valueForKeyPath:@"foregroundView"] subviews];
//NSLog(@"%@",childensArray);
/*
UIStatusBarServiceItemView
UIStatusBarDataNetworkItemView
UIStatusBarBatteryItemView
UIStatusBarTimeItemView
*/
int netWorkType = 0;
for (id child in childensArray) {
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
unsigned int outCount = 0;
Ivar *ivars = class_copyIvarList([child class], &outCount);
for (int i =0; i<outCount; i++) {
Ivar ivar = ivars[i];
const char *ivarName = ivar_getName(ivar);
/*
dataNetworkType 0 - 无网络 ; 1 - 2G ; 2 - 3G ; 3 - 4G ; 5 - WIFI;
wifiStrengthRaw
wifiStrengthBars
enableRSSI
showRSSI
*/
//NSString * propertyName=[NSString stringWithCString:ivarName encoding:NSUTF8StringEncoding];
//网络状态
netWorkType = [[child valueForKey:@"dataNetworkType"] intValue];
}
}
}
switch (netWorkType) {
case 0:
NSLog(@"无网络");
break;
case 1:
NSLog(@"2G网络");
break;
case 2:
NSLog(@"3G网络");
break;
case 3:
NSLog(@"4G网络");
break;
case 5:
NSLog(@"WIFI网络");
break;
default:
break;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end