iOS获取当前网络状态

首先,我们需要拿到状态栏,然后通过runtime去探讨状态栏内部的组成结构

需要#import <objc/message.h>(xcode6下不导入也没影响)

这里为了方便定义枚举

typedef  enum {
    NO_G_WORK = 0,
    TWO_G_WORK,
    THREE_G_WORK,
    FOUR_G_WORK,
    WIFI = 5,
}NET_STATUS;
 1 #pragma mark - getNetworkStatus
 2 - (void)getNetworkStatus
 3 {
 4     // 状态栏是由当前app控制的,首先获取当前app
 5     UIApplication *app = [UIApplication sharedApplication];
 6     
 7     NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
 8     
 9     NET_STATUS type = 0;
10     for (id child in children) {
11         if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
12             type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
13         }
14     }
15 
16     switch (type) {
17         case NO_G_WORK:
18             NSLog(@"NO_G_WORK");
19             break;
20         case TWO_G_WORK:
21             NSLog(@"TWO_G_WORK");
22             break;
23         case THREE_G_WORK:
24             NSLog(@"THREE_G_WORK");
25             break;
26         case FOUR_G_WORK:
27             NSLog(@"FOUR_G_WORK");
28             break;
29         case WIFI:
30             NSLog(@"WIFI");
31             break;
32             
33         default:
34             break;
35     }
36     
37 }

调用上面的方法

- (void)viewWillAppear:(BOOL)animated
{
    [self getNetworkStatus];
}

打印出的type数字对应的网络状态依次是:0 - 无网络; 1 - 2G; 2 - 3G; 3 - 4G; 5 - WIFI

posted on 2014-09-20 22:21  李园春秋  阅读(410)  评论(0编辑  收藏  举报

导航