iOS状态栏操作之获取WiFi信号强度,网络类型,运营商,电池电量,系统时间等

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wenmingzheng/article/details/50475671

iOS状态栏操作之获取WiFi信号强度,WiFi名字和IP,网络类型,运营商,电池电量,系统时间等

此篇文章讲述iOS中的状态栏

iOS开发中对状态栏的操作比较少,因为状态栏是系统级别的View,是受苹果保护的,不可以随便更改,不可以随便遮挡住。如果违反这些苹果的规范,那么APP将有可能上不了架。笔者就曾写过一个APP,因状态栏被提示框遮挡而杯具(被拒)了。

一、操作状态栏的样式

iOS开发中最常见的对状态栏的操作就是设置状态栏的样式,比如:

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

(此样式的状态栏中的字为白色,所以用在导航栏为深色的情况下,例如黑色或者红色的导航栏)还有

 [[UIApplication  
 sharedApplication]setStatusBarStyle:UIStatusBarStyleDefault];

(此样式的状态栏中的字为黑色色,所以用在导航栏为浅色色的情况下,比如白色的导航栏)
如果你设置了,发现状态栏没反应,那么你要去info.plist中加一个key,这个key为View controller-based status bar appearance,对应的value为NO。这样每个vc中就可以随便设置状态栏的样式了。

二、操作状态栏的大小、背景颜色、位置

那么实际上我们可以拿到状态栏这个UIView对象。为了不让苹果看到我们用了某某私有API,我们这样做:

- (UIView*)statusBarView;
{
    UIView *statusBar = nil;
    NSData *data = [NSData dataWithBytes:(unsigned char []){0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x42, 0x61, 0x72} length:9];
    NSString *key = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    id object = [UIApplication sharedApplication];
    if ([object respondsToSelector:NSSelectorFromString(key)]) statusBar = [object valueForKey:key];
    return statusBar;
}

调用这个方法就可以拿到系统的状态栏对象,是个UIView类型的对象,那么UIView我们最熟悉了,我们可以改变状态栏的颜色,背景颜色(backgroundColor)、大小位置(frame)等等。

三、操作状态栏,得到网络类型、运营商、电池电量等

定义一个工具类StatusBarTool,用来获取网络类型,运营商,电池电量,显示的系统时间等信息。那么直接看代码:
.h文件

 #import < Foundation/Foundation.h >
 #import  < UIKit/UIKit.h >

//0 - 无网络 ; 1 - 2G ; 2 - 3G ; 3 - 4G ; 5 - WIFI

typedef NS_ENUM(NSUInteger, NetWorkType) {
    NetWorkTypeNone=0,
    NetWorkType2G=1,
    NetWorkType3G=2,
    NetWorkType4G=3,
    NetWorkTypeWiFI=5,
};


@interface StatusBarTool : NSObject
/**
 *  
 *
 *  @return 当前网络类型
 */
+(NetWorkType )currentNetworkType;


/**
 *
 *
 *  @return SIM卡所属的运营商(公司)
 */
+(NSString *)serviceCompany;

/**
 *
 *
 *  @return 当前电池电量百分比
 */
+(NSString *)currentBatteryPercent;

/**
 *
 *
 *  @return 当前时间显示的字符串
 */
+(NSString *)currentTimeString;

@end

.m实现文件(很重要)

 #import "StatusBarTool.h"

 @ implementation StatusBarTool


+(NSString *)currentBatteryPercent{ 
NSArray *infoArray = [[[[UIApplication sharedApplication] valueForKeyPath:@”statusBar”] valueForKeyPath:@”foregroundView”] subviews];

for (id info in infoArray)
{
    if ([info isKindOfClass:NSClassFromString(@"UIStatusBarBatteryPercentItemView")])
    {
        NSString *percentString = [info valueForKeyPath:@"percentString"];
        NSLog(@"电量��为:%@",percentString);
        return percentString;
    }
}
return @"";
} 
+(NetWorkType )currentNetworkType{

NSArray *infoArray = [[[[UIApplication sharedApplication] valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];

NetWorkType type;
for (id info in infoArray)
{
    if ([info isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
        type = [[info valueForKeyPath:@"dataNetworkType"] integerValue];
        NSLog(@"----%lu", (unsigned long)type);

        return (NetWorkType)type;
    }

}
return NetWorkTypeNone;
} 
+(NSString *)currentTimeString{ 
NSArray *infoArray = [[[[UIApplication sharedApplication] valueForKeyPath:@”statusBar”] valueForKeyPath:@”foregroundView”] subviews];

for (id info in infoArray)
{
    if ([info isKindOfClass:NSClassFromString(@"UIStatusBarTimeItemView")])
    {
        NSString *timeString = [info valueForKeyPath:@"timeString"];
        NSLog(@"当前显示时间为:%@",timeString);
        return timeString;
    }
}
return @"";
}

+(NSString *)serviceCompany{ 
NSArray *infoArray = [[[[UIApplication sharedApplication] valueForKeyPath:@”statusBar”] valueForKeyPath:@”foregroundView”] subviews];

for (id info in infoArray)
{
    if ([info isKindOfClass:NSClassFromString(@"UIStatusBarServiceItemView")])
    {
        NSString *serviceString = [info valueForKeyPath:@"serviceString"];
        NSLog(@"公司为:%@",serviceString);
        return serviceString;
    }
}
return @"";
} 
@end

//用StatusBarTool这个类的时候

NSString *company = [StatusBarTool serviceCompany]; 
NSLog(@”company = %@”,company); 
company = 中国移动 
NetWorkType type = [StatusBarTool currentNetworkType]; 
NSLog(@”type = %ld”,type); 
type = 55代表Wi-Fi) 
/*typedef NS_ENUM(NSUInteger, NetWorkType) { 
NetWorkTypeNone=0, 
NetWorkType2G=1, 
NetWorkType3G=2, 
NetWorkType4G=3, 
NetWorkTypeWiFI=5, 
};*/ 
NSString *batteryPercent = [StatusBarTool currentBatteryPercent]; 
NSLog(@”batteryPercent = %@”,batteryPercent); 
batteryPercent �� = 96%

NSString *timeString = [StatusBarTool currentTimeString]; 
NSLog(@”timeString = %@”,timeString); 
timeString = 12:57

四、获取WiFi信号强度
这里写图片描述

虽然各种直接获取信号强度的api都被封杀了。但是还有一个另类的黑魔法可以获取到。那就是遍历UIStatusBar了(注意:Wi-Fi列表和列表中的Wi-Fi信号强度是获取不到的,只能得到自己当前iPhone链接的Wi-Fi的名字和对应的Wi-Fi信号强度。)

另外:不要留言说,1、博主,我想问一下,人家万能钥匙怎么实现的呢?
2、不对,博主,AppStore上面很多app都可以获取到WiFi列表。请问怎么实现的?

看下面的代码

- (int )getSignalStrength{
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    UIView *dataNetworkItemView = nil;

    for (UIView * subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            dataNetworkItemView = subview;
            break;
        }
    }

    int signalStrength = [[dataNetworkItemView valueForKey:@"_wifiStrengthBars"] intValue];

    NSLog(@"signal %d", signalStrength);
    return signalStrength;
}

五、获取WiFi的名称,IP地址

WiFi的名称就是WiFi的SSID,也就是我们看到列表中的WiFi的名字。
首先我们要导入三个相关的头文件,代码如下:

#import <SystemConfiguration/CaptiveNetwork.h>
#import <ifaddrs.h>
#import <arpa/inet.h>

- (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;

    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }

            temp_addr = temp_addr->ifa_next;
        }
    }

    // Free memory
    freeifaddrs(interfaces);

    return address;
}
-(NSString *)getWifiName
{
    NSString *wifiName = nil;

    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();

    if (!wifiInterfaces) {
        return nil;
    }

    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;

    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));

        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            NSLog(@"network info -> %@", networkInfo);
            wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];

            CFRelease(dictRef);
        }
    }

    CFRelease(wifiInterfaces);
    return wifiName;
}

好了,至此我们已经拿到了网络状态,WiFi信号强度,WiFi名字和IP地址,运营商,电池电量百分比,时间显示等信息了。其实遍历UIStatusBar还可以获取到其他的有用信息,这里就不一一列举了,只列举了常用的。

最后欢迎大家关注文明的iOS开发公众号:
方式1、搜索:“iOS开发by文明”
方式2、扫描下方二维码

这里写图片描述
另外博主维护一个iOS开发技术支持群:479259423,进群必须改名,群名片格式:城市-iOS-名字,例如广州-iOS-文明。手机可以加,电脑加不了。

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页