本文列出了各种iOS的基础信息的获取方式。

系统信息

  • 设备型号
1
struct utsname systemInfo;
uname(&systemInfo);
NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
  • 操作系统名称
1
UIDevice *device = [UIDevice currentDevice];
[device systemName];
  • 操作系统版本
1
UIDevice *device = [UIDevice currentDevice];
[device systemVersion];
  • 设备型号,如: iPad,iPod等。
1
UIDevice *device = [UIDevice currentDevice];
[device model];
  • 屏幕分辨率
1
UIScreen *screen     = [UIScreen mainScreen];
CGSize screenSize    = [[UIScreen mainScreen] bounds].size;
CGFloat scale        = screen.scale;
int screenX          = screenSize.width * scale;
int screenY          = screenSize.height *scale;
NSString *resolution = [NSString stringWithFormat:@"%d*%d", screenX, screenY];
  • 电池电量
1
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter] addObserverForName:UIDeviceBatteryLevelDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) {
     // Level has changed
     NSLog(@"Battery Level Change");
     NSLog(@"电池电量:%.2f", [UIDevice currentDevice].batteryLevel);
 }];

网络信息

需要引入库:CoreTelephony.framework

  • 网络类型,如:WiFi,4G等。
1
NSString *networktype = nil;
NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"]subviews];
NSNumber *dataNetworkItemView = nil;
for (id subview in subviews) {
    if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
        dataNetworkItemView = subview;
        break;
    }
}
switch ([[dataNetworkItemView valueForKey:@"dataNetworkType"]integerValue]) {
    case 0:
        networktype = @"UNKNOW";
        break;
    case 1:
        networktype = @"2G";
        break;
    case 2:
        networktype = @"3G";
        break;
    case 3:
        networktype = @"4G";
        break;
    case 4:
        networktype = @"LTE";
        break;
    case 5:
        networktype = @"Wi-Fi";
        break;
    default:
        break;
}
return networktype;
  • 蜂窝网络类型
1
CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
if ( [telephonyInfo respondsToSelector:@selector(currentRadioAccessTechnology)] ) {
    id radioAccessType = [telephonyInfo performSelector:@selector(currentRadioAccessTechnology)
                                             withObject:nil];
    
    if ( [radioAccessType isKindOfClass:[NSString class]] ) {
        NSString *accessType = (NSString *)radioAccessType;
        if ( [accessType hasPrefix:@"CTRadioAccessTechnology"] && accessType.length >= 23 ) {
            NSString *accessTypeStr = [accessType substringFromIndex:23];
            return accessTypeStr;
        }
    }
}
    
return @"UNKNOW";
  • 运营商信息
1
CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier    = [telephonyInfo subscriberCellularProvider];
NSString *carrierName = [carrier carrierName];
if ( nil != carrierName ) {
    return carrierName;
}
return @"UNKNOW";

应用状态

  • APP启动,或者由后台进入前台
1
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
  • APP从后台进入前台
1
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationBecomeActive) name:UIApplicationWillEnterForegroundNotification object:nil];
  • APP进入后台
1
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name: UIApplicationDidEnterBackgroundNotification object:nil];
  • APP在前台锁屏
1
#import <notify.h>
#define NotificationLock CFSTR("com.apple.springboard.lockcomplete")
#define NotificationChange CFSTR("com.apple.springboard.lockstate")
#define NotificationPwdUI CFSTR("com.apple.springboard.hasBlankedScreen")

static void screenLockStateChanged(CFNotificationCenterRef center,void* observer,CFStringRef name,const void* object,CFDictionaryRef userInfo)
{
	NSString* lockstate = (__bridge NSString*)name;
	if ([lockstate isEqualToString:(__bridge  NSString*)NotificationLock]) {
	    NSLog(@"locked.");
	} else {
	    NSLog(@"lock state changed.");
	}
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
	CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
	CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
	return YES;
}
  • APP在后台锁屏,通过循环的方式检测
1
static void setScreenStateCb()
{
uint64_t locked;

__block int token = 0;
notify_register_dispatch("com.apple.springboard.lockstate",&token,dispatch_get_main_queue(),^(int t){
});
	notify_get_state(token, &locked);
	NSLog(@"%d",(int)locked);
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
	while (YES) {
	    setScreenStateCb();
	    sleep(5); // 循环5s
	}
}
  • 获取当前APP的CPU使用率
1
kern_return_t kr;
task_info_data_t tinfo;
mach_msg_type_number_t task_info_count;
    
task_info_count = TASK_INFO_MAX;
kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
if (kr != KERN_SUCCESS) {
    return;
}
    
task_basic_info_t      basic_info;
thread_array_t         thread_list;
mach_msg_type_number_t thread_count;
    
thread_info_data_t     thinfo;
mach_msg_type_number_t thread_info_count;
    
thread_basic_info_t basic_info_th;
uint32_t stat_thread = 0; // Mach threads
    
basic_info = (task_basic_info_t)tinfo;
    
// get threads in the task
kr = task_threads(mach_task_self(), &thread_list, &thread_count);
if (kr != KERN_SUCCESS) {
    return;
}
if (thread_count > 0)
    stat_thread += thread_count;
    
long tot_sec = 0;
long tot_usec = 0;
float tot_cpu = 0;
int j;
    
for (j = 0; j < thread_count; j++)
{
    thread_info_count = THREAD_INFO_MAX;
    kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
                     (thread_info_t)thinfo, &thread_info_count);
    if (kr != KERN_SUCCESS) {
        return;
    }
    
    basic_info_th = (thread_basic_info_t)thinfo;
    
    if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
        tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
        tot_usec = tot_usec + basic_info_th->system_time.microseconds + basic_info_th->system_time.microseconds;
        tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0;
    }
    
} // for each thread
    
kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
assert(kr == KERN_SUCCESS);
    
NSLog(@"CPU Usage: %f \n", tot_cpu);
  • 获取当前APP的内存使用情况
1
task_basic_info_data_t taskInfo;
mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
kern_return_t kernReturn = task_info(mach_task_self(),
                                     TASK_BASIC_INFO, (task_info_t)&taskInfo, &infoCount);

if(kernReturn != KERN_SUCCESS) {
    return;
}
    
NSLog(@"Memory Usage: %f", taskInfo.resident_size / 1024.0 / 1024.0);
iOS
iOS