iOS获取设备各种硬件信息

1.NSLog(@"%@",[[UIDevice currentDevice] systemVersion]);//系统版本

2.获取手机型号 需要头文件 #import

- (NSString *)iphoneType {

struct utsname systemInfo;

uname(&systemInfo);

NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];

if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";

if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";

if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";

if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";

if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";

if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";

if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";

if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";

if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";

if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";

if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";

if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";

if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";

if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";

if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";

if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";

if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";

if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";

if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";

if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";

if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";

if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";

if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";

if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";

if ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G";

if ([platform isEqualToString:@"iPad1,1"]) return @"iPad 1G";

if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2";

if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2";

if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2";

if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2";

if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini 1G";

if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini 1G";

if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini 1G";

if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3";

if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3";

if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3";

if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4";

if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4";

if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4";

if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air";

if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air";

if ([platform isEqualToString:@"iPad4,3"]) return @"iPad Air";

if ([platform isEqualToString:@"iPad4,4"]) return @"iPad Mini 2G";

if ([platform isEqualToString:@"iPad4,5"]) return @"iPad Mini 2G";

if ([platform isEqualToString:@"iPad4,6"]) return @"iPad Mini 2G";

if ([platform isEqualToString:@"i386"]) return @"iPhone Simulator";

if ([platform isEqualToString:@"x86_64"]) return @"iPhone Simulator";

return platform;

}

3.NSString *identifierStr = [[[UIDevice currentDevice] identifierForVendor] UUIDString];

NSLog(@"设备唯一标识符:%@",identifierStr);

4.[UIDevice currentDevice].batteryMonitoringEnabled = YES; 

double deviceLevel = [UIDevice currentDevice].batteryLevel;

获取当前剩余电量, 我们通常采用上述方法即苹果官方文档提供的。

它返回的是0.00-1.00之间的浮点值。  另外, -1.00表示模拟器。

但是仔细观察它的返回值,  是以0.05递变的。 折算成100% 也就是以5%来递变的。

也就是说,很不精确。

下面方法。相当精确, 误差保持在1%以内。

我们知道, Mac下有个IOKit.framework库。 它可以计算出我们需要的电量。

如果我们要使用它的话, (iOS是不提供的) 可以先建立一个Mac下的工程, 找到IOKit.framework,那IOKit.framework里面的IOPowerSources.h和IOPSKeys.h拷贝到你的iOS项目中。另外, 还需要把IOKit也导入到你的工程中去。(请使用真机调试)

- (NSString*)batteryLevel

{

CFTypeRef blob = IOPSCopyPowerSourcesInfo();

CFArrayRef sources = IOPSCopyPowerSourcesList(blob);

CFDictionaryRef pSource = NULL;

const void *psValue;

int numOfSources = CFArrayGetCount(sources);

if (numOfSources == 0)

{

CFRelease(blob);

CFRelease(sources);

NSLog(@"qhk: Error in CFArrayGetCount");

return nil;

}

for (int i = 0 ;i < numOfSources ; i++)

{

pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i));

if (!pSource)

{

CFRelease(blob);

CFRelease(sources);

NSLog(@"qhk: Error in IOPSGetPowerSourceDescription");

return nil;

}

psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey));

int curCapacity = 0;

int maxCapacity = 0;

//                double percent;

psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey));

CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);

psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey));

CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);

//                percent = ((double)curCapacity/(double)maxCapacity * 100.0f);

NSNumber* no1 = [NSNumber numberWithInt:curCapacity];

NSNumber* no2= [NSNumber numberWithInt:maxCapacity];

CFRelease(blob);

CFRelease(sources);

return [NSDictionary dictionaryWithObjectsAndKeys:no1, @"no1", no2, @"no2", nil];

//                return percent;

//                return (NSInteger)(percent + 0.5f);

}

//#endif

CFRelease(blob);

CFRelease(sources);

return nil;

}

5.#pragma mark 获取ip地址 头文件 #include #include #include

- (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;

}

6.#pragma mark  内存使用状况  头文件 #import

//获取总内存大小 (单位:MB)

-(double)getTotalMemorySize

{

  return [NSProcessInfo processInfo].physicalMemory/1024/1024;

}

// 获取当前设备可用内存(单位:MB)

- (double)availableMemory

{

vm_statistics_data_t vmStats;

mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;

kern_return_t kernReturn = host_statistics(mach_host_self(),

HOST_VM_INFO,

(host_info_t)&vmStats,

&infoCount);

if (kernReturn != KERN_SUCCESS) {

return NSNotFound;

}

return ((vm_page_size *vmStats.free_count) / 1024.0) / 1024.0;

}

7.#pragma mark  获取当前任务所占用的内存(单位:MB)  头文件 #import

- (double)usedMemory

{

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 NSNotFound;

}

return taskInfo.resident_size / 1024.0 / 1024.0;

}

8.//NSFileManager包含非常丰富的信息,通过下面的方法可很容易的获取系统磁盘的大小和可用磁盘的大小

#pragma mark 总的磁盘空间

- (float)getTotalDiskspace{

float totalSpace;

NSError *error = nil;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];

if (dictionary) {

NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];

totalSpace = [fileSystemSizeInBytes floatValue]/1024.0f/1024.0f/1024.0f;

} else {

totalSpace = 0;

}

return totalSpace;

}

#pragma mark 可用磁盘空间

- (float)getFreeDiskspace{

float freeSpace;

NSError *error = nil;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];

if (dictionary) {

NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];

freeSpace = [freeFileSystemSizeInBytes floatValue]/1024.0f/1024.0f/1024.0f;

} else {

freeSpace = 0;

}

return freeSpace;

}

9.获取网络类型(AFNetWorking)

AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];

[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

switch (status) {

case AFNetworkReachabilityStatusUnknown: {

[Const warningTitle:@"未知网络"];

break;

}

case AFNetworkReachabilityStatusNotReachable: {

[Const warningTitle:@"无连接"];

break;

}

case AFNetworkReachabilityStatusReachableViaWWAN: {

[Const warningTitle:@"当前为移动流量"];

break;

}

case AFNetworkReachabilityStatusReachableViaWiFi: {

[Const warningTitle:@"当前链接wifi"];

break;

}

default: {

break;

}

}

}];

[manager startMonitoring];

10.获取当前APP的cpu占用 头文件 #import

//app的cpu占用

- (float)cpu_usage

{

kern_return_t kr = { 0 };

task_info_data_t tinfo = { 0 };

mach_msg_type_number_t task_info_count = TASK_INFO_MAX;

kr = task_info( mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count );

if ( KERN_SUCCESS != kr )

return 0.0f;

task_basic_info_t basic_info = { 0 };

thread_array_t thread_list = { 0 };

mach_msg_type_number_t thread_count = { 0 };

thread_info_data_t thinfo = { 0 };

thread_basic_info_t basic_info_th = { 0 };

basic_info = (task_basic_info_t)tinfo;

// get threads in the task

kr = task_threads( mach_task_self(), &thread_list, &thread_count );

if ( KERN_SUCCESS != kr )

return 0.0f;

long tot_sec = 0;

long tot_usec = 0;

float tot_cpu = 0;

for ( int i = 0; i < thread_count; i++ )

{

mach_msg_type_number_t thread_info_count = THREAD_INFO_MAX;

kr = thread_info( thread_list[i], THREAD_BASIC_INFO, (thread_info_t)thinfo, &thread_info_count );

if ( KERN_SUCCESS != kr )

return 0.0f;

basic_info_th = (thread_basic_info_t)thinfo;

if ( 0 == (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;

}

}

kr = vm_deallocate( mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t) );

if ( KERN_SUCCESS != kr )

return 0.0f;

return tot_cpu;

}

11.获取手机运行时长 头文件#include

//获取手机运行时长 单位秒

-(time_t)timeRun

{

struct timeval boottime;

int mib[2] = {CTL_KERN, KERN_BOOTTIME};

size_t size = sizeof(boottime);

time_t now;

time_t uptime = -1;

(void)time(&now);

if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && boottime.tv_sec != 0)

{

uptime = now - boottime.tv_sec;

}

return uptime;

}

- (void )timeRunDay

{

double time = (double)[self timeRun];

//Day

NSInteger timeDay = 0;

//Hour

NSInteger timeHour = 0;

//Minute

NSInteger timeMinute = 0;

//Second

NSInteger timeSecond = 0;

if (time>=60*60*24) {

timeDay = (NSInteger)time/60/60/24;

}

if (time>60*60) {

timeHour = (NSInteger)time%(60*60*24)/(60*60);

}

if (time>60) {

timeMinute = (NSInteger)time%(60*60*24)%(60*60)/60;

}

timeSecond = (NSInteger)time%(60*60*24)%(60*60)%60;

NSLog(@"此设备已经运行 %ld天 %ld时 %ld分 %ld秒",(long)timeDay,(long)timeHour,(long)timeMinute,(long)timeSecond);

}

//根据运行时长计算开机时间

- (NSString *)bootTime

{

double time = (double)[self timeRun];

//Day

NSInteger timeDay = 0;

//Hour

NSInteger timeHour = 0;

//Minute

NSInteger timeMinute = 0;

//Second

NSInteger timeSecond = 0;

if (time>=60*60*24) {

timeDay = (NSInteger)time/60/60/24;

}

if (time>60*60) {

timeHour = (NSInteger)time%(60*60*24)/(60*60);

}

if (time>60) {

timeMinute = (NSInteger)time%(60*60*24)%(60*60)/60;

}

timeSecond = (NSInteger)time%(60*60*24)%(60*60)%60;

//得到当前的时间

NSDate * mydate = [NSDate date];

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];

NSLog(@"---当前的时间的字符串 =%@",currentDateStr);

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSDateComponents *comps = nil;

comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitMonth fromDate:mydate];

NSDateComponents *adcomps = [[NSDateComponents alloc] init];

[adcomps setDay:-timeDay];//当前时间几天前

[adcomps setHour:-timeHour];

[adcomps setMinute:-timeMinute];

[adcomps setSecond:-timeSecond];

NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0];

NSString *beforDate = [dateFormatter stringFromDate:newdate];

NSLog(@"---开机时间 =%@",beforDate);

return beforDate;

}

12.获取开机时间算起设备消耗流量 头文件 #include #include #include

-(NSDictionary *)DataCounters

{

struct ifaddrs *addrs;

const struct ifaddrs *cursor;

u_int32_t WiFiSent = 0;

u_int32_t WiFiReceived = 0;

u_int32_t WWANSent = 0;

u_int32_t WWANReceived = 0;

if (getifaddrs(&addrs) == 0)

{

cursor = addrs;

while (cursor != NULL)

{

if (cursor->ifa_addr->sa_family == AF_LINK)

{

#ifdef DEBUG

const struct if_data *ifa_data = (struct if_data *)cursor->ifa_data;

if(ifa_data != NULL)

{

NSLog(@"Interface name %s: sent %tu received %tu",cursor->ifa_name,ifa_data->ifi_obytes,ifa_data->ifi_ibytes);

}

#endif

// name of interfaces:

// en0 is WiFi

// pdp_ip0 is WWAN

NSString *name = [NSString stringWithFormat:@"%s",cursor->ifa_name];

if ([name hasPrefix:@"en"])

{

const struct if_data *ifa_data = (struct if_data *)cursor->ifa_data;

if(ifa_data != NULL)

{

WiFiSent += ifa_data->ifi_obytes;

WiFiReceived += ifa_data->ifi_ibytes;

}

}

if ([name hasPrefix:@"pdp_ip"])

{

const struct if_data *ifa_data = (struct if_data *)cursor->ifa_data;

if(ifa_data != NULL)

{

WWANSent += ifa_data->ifi_obytes;

WWANReceived += ifa_data->ifi_ibytes;

}

}

}

cursor = cursor->ifa_next;

}

freeifaddrs(addrs);

}

NSString *stringsdsdsd = [NSString stringWithFormat:@"wifi 发送:%.2f wifi 收到:%.2f MBn 2g/3g/4g 发送 :%.2f MBn 2g/3g/4g 收到:%.2f MBn",WiFiSent/1024.0/1024.0,WiFiReceived/1024.0/1024.0,WWANSent/1024.0/1024.0,WWANReceived/1024.0/1024.0];

label2.text = stringsdsdsd;

return @{DataCounterKeyWiFiSent:[NSNumber numberWithUnsignedInt:WiFiSent],

DataCounterKeyWiFiReceived:[NSNumber numberWithUnsignedInt:WiFiReceived],

DataCounterKeyWWANSent:[NSNumber numberWithUnsignedInt:WWANSent],

DataCounterKeyWWANReceived:[NSNumber numberWithUnsignedInt:WWANReceived]};

}

13.获取子网掩码,广播地址及IP 头文件 #include #import #import #include #import "getgateway.h"

#pragma mark - 获取路由器地址

- (NSString *) routerIp {

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)

/*/

int i=255;

while((i--)>0)

//*/

{

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 //ifa_addr

//ifa->ifa_dstaddr is the broadcast address, which explains the "255's"

//                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];

address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

//routerIP----192.168.1.255 广播地址

NSLog(@"broadcast address--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)]);

//--192.168.1.106 本机地址

NSLog(@"local device ip--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]);

//--255.255.255.0 子网掩码地址

NSLog(@"netmask--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)]);

//--en0 端口地址

NSLog(@"interface--%@",[NSString stringWithUTF8String:temp_addr->ifa_name]);

}

}

temp_addr = temp_addr->ifa_next;

}

}

// Free memory

freeifaddrs(interfaces);

in_addr_t i =inet_addr([address cStringUsingEncoding:NSUTF8StringEncoding]);

in_addr_t* x =&i;

unsigned char *s = getdefaultgateway(x);

NSString *ip=[NSString stringWithFormat:@"%d.%d.%d.%d",s[0],s[1],s[2],s[3]];

free(s);

return ip;

}

14.//获取sim卡信息 倒入SystemConfiguration和CoreTelephony。头文件 #import #import #import

- (void)simMessage

{

CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];

CTCarrier *carrier = networkInfo.subscriberCellularProvider;

NSString *carrier_country_code = carrier.isoCountryCode;

if (carrier_country_code == nil) {

carrier_country_code = @"";

}

//国家编号

NSString *CountryCode = carrier.mobileCountryCode;

if (CountryCode == nil) {

CountryCode = @"";

}

NSLog(@"国家编号 = %@",CountryCode);

//网络供应商编码

NSString *NetworkCode = carrier.mobileNetworkCode;

if (NetworkCode == nil)

{

NetworkCode = @"";

}

NSLog(@"网络供应商编码 = %@",NetworkCode);

NSString *mobile_country_code = [NSString stringWithFormat:@"%@%@",CountryCode,NetworkCode];

if (mobile_country_code == nil)

{

mobile_country_code = @"";

}

NSString *carrier_name = nil;    //网络运营商的名字

NSString *code = [carrier mobileNetworkCode];

if ([code isEqualToString:@"00"] || [code isEqualToString:@"02"] || [code isEqualToString:@"07"]) {

//移动

carrier_name = @"CMCC";

}

if ([code isEqualToString:@"03"] || [code isEqualToString:@"05"])

{

// ret = @"电信";

carrier_name =  @"CTCC";

}

if ([code isEqualToString:@"01"] || [code isEqualToString:@"06"])

{

// ret = @"联通";

carrier_name =  @"CUCC";

}

if (code == nil)

{

carrier_name = @"";

}

carrier_name = [[NSString stringWithFormat:@"%@-%@",carrier_name,carrier.carrierName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

}

15.//获取cpu核数 头文件 #include

- (unsigned int)countofCores

{

unsigned int ncpu;

size_t len = sizeof(ncpu);

sysctlbyname("hw.ncpu", &ncpu, &len, NULL, 0);

return ncpu;

}

你可能感兴趣的:(iOS获取设备各种硬件信息)