[iOS] - 获取WIFI信号强度

作者: SwiftBest | 来源:发表于2016-09-09 11:44 被阅读936次

    之前获取信号强度的API都不能用了,最近看到一个黑魔法,遍历UIStatusBar获取。

    - (void)getSignalStrength{
        UIApplication *app = [UIApplication sharedApplication];
        NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
        NSString *dataNetworkItemView = nil;
    
        for (id subview in subviews) {
            if([subview isKindOfClass:    [NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            dataNetworkItemView = subview;
            break;
            }
         }
    
        int signalStrength = [[dataNetworkItemView valueForKey:@"_wifiStrengthBars"] intValue];
    
        NSLog(@"signal %d", signalStrength);
    }
    

    我们还可以遍历UIStatusBar,获取到网络连接类型。

    - (void)getNetworkType
    {
        UIApplication *app = [UIApplication sharedApplication];
        NSArray *subviews = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
        for (id subview in subviews) {
            if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            int networkType = [[subview valueForKeyPath:@"dataNetworkType"] intValue];
            switch (networkType) {
                case 0:
                    NSLog(@"NONE");
                    break;
                case 1:
                    NSLog(@"2G");
                    break;
                case 2:
                    NSLog(@"3G");
                    break;
                case 3:
                    NSLog(@"4G");
                    break;
                case 5:
                {
                    NSLog(@"WIFI");
                }
                    break;
                default:
                    break;
                }
            }
        }
    }

    相关文章

      网友评论

        本文标题:[iOS] - 获取WIFI信号强度

        本文链接:https://www.haomeiwen.com/subject/xppeettx.html