首先創(chuàng)建StatusBarTool文件
再拷貝下面的代碼
此方法用到了私有API(不建議使用)
.h文件代碼
#import <UIKit/UIKit.h>
typedef enum {
NetWorkTypeNone = 0, //未知網(wǎng)絡(luò)或沒(méi)有網(wǎng)絡(luò)
NetWorkType2G = 1, //2G網(wǎng)絡(luò)
NetWorkType3G = 2, //3G網(wǎng)絡(luò)
NetWorkType4G = 3, //4G網(wǎng)絡(luò)
NetWorkTypeWiFi = 5, //WiFi網(wǎng)絡(luò)
} NetWorkType;
@interface StatusBarTool : NSObject
/** 獲取當(dāng)前網(wǎng)絡(luò)狀態(tài) */
+ (NetWorkType)currentNetWorkType;
/** 獲取當(dāng)前網(wǎng)絡(luò)運(yùn)營(yíng)商 */
+ (NSString *)serviceCompany;
/** 獲取當(dāng)前電池電量 */
+ (NSString *)currentBatteryPercent;
/** 獲取當(dāng)前時(shí)間 */
+ (NSString *)currentTimeString;
@end
.m文件代碼
#import "StatusBarTool.h"
@implementation StatusBarTool
+ (NSString *)currentBatteryPercent
{
NSArray *infoArray = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
for (id info in infoArray) {
if ([info isKindOfClass:NSClassFromString(@"UIStatusBarBatteryPercentItemView")]) {
NSString *percentString = [info valueForKey:@"percentString"];
NSLog(@"電量為: %@",percentString);
return percentString;
}
}
return @"";
}
+ (NetWorkType)currentNetWorkType
{
NSArray *infoArray = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
NetWorkType type;
for (id info in infoArray) {
if ([info isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
type = [[info valueForKey:@"dataNetworkType"] intValue];
NSLog(@"網(wǎng)絡(luò)狀態(tài): %d",type);
return type;
}
}
return NetWorkTypeNone;
}
+ (NSString *)currentTimeString
{
NSArray *infoArray = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
for (id info in infoArray) {
if ([info isKindOfClass:NSClassFromString(@"UIStatusBarTimeItemView")]) {
NSString *timeString = [info valueForKey:@"timeString"];
NSLog(@"當(dāng)前時(shí)間為:%@",timeString);
return timeString;
}
}
return @"";
}
+ (NSString *)serviceCompany
{
NSArray *infoArray = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
for (id info in infoArray) {
if ([info isKindOfClass:NSClassFromString(@"UIStatusBarServiceItemView")]) {
NSString *serviceString = [info valueForKey:@"serviceString"];
NSLog(@"運(yùn)營(yíng)商:%@",serviceString);
return serviceString;
}
}
return @"";
}
@end