获取手机各种信息
引言:
应用中经常会用到获取手机各种信息。
# 一. 获取手机电量
// 获取状态栏
UIStatusBar *statusBar = [[UIApplication sharedApplication] valueForKey:@"_statusBar"];
// 获取状态栏的前视图(视图中包括运营商,电池电量,信号,时间等等)
UIView *foregroundView = [[[[UIApplication sharedApplication] valueForKey:@"_statusBar"] subviews] lastObject];
// 获取到状态栏前视图的所有控件
NSArray *statusBarSubviews = [[[[[UIApplication sharedApplication] valueForKey:@"_statusBar"] subviews] lastObject] subviews];
for (id subview in statusBarSubviews) {
// 通过类名来获得电量
if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarBatteryPercentItemView")])
{
//系统方法直接通过键值对拿到100%
result = [subview valueForKey:@"_percentString"];
}
}
// 得到的电量
return result;
# 二. 获取手机信息
# 1. 电池状态
NSInteger i = [UIDevice currentDevice].systemName;
/**
* UIDeviceBatteryStateUnknown:无法取得充电状态情况
UIDeviceBatteryStateUnplugged:非充电状态
UIDeviceBatteryStateCharging:充电状态
UIDeviceBatteryStateFull:充满状态(连接充电器充满状态)
*/
# 2. 设备所有者名称
UIDevice *device = [UIDevice currentDevice];
NSString *name = device.name;
# 3. 设备类型
// iphone ipad iwatch
NSString *name = [UIDevice currentDevice].model;
# 4. 系统类型
// iOS
NSString *name = [UIDevice currentDevice].systemName;
# 5. 系统版本号
// 10.1
NSString *name = [UIDevice currentDevice].systemVersion;
# 6. 获取设备唯一标识符
// 6C0AA68D-303F-4422-9E4C-5FED956F9408
UIDevice *device = [UIDevice currentDevice];
NSLog(@"%@", [device.identifierForVendor UUIDString]);
# 7. 运行商的名称
导入两个头文件:
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
NSString *operators = [info subscriberCellularProvider].carrierName;
NSLog(@"%@", operators);
# 8. 网络状态
NSArray *children = [[[[UIApplication sharedApplication] valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
NSString *state = [[NSString alloc] init];
int netType = 0;
//获取到网络返回码
for (id child in children) {
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
//获取到状态栏
netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
switch (netType) {
case 0:
state = @"无网络";//无网模式
break;
case 1:
state = @"2G";
break;
case 2:
state = @"3G";
break;
case 3:
state = @"4G";
break;
case 5:
state = @"WIFI";
break;
default:
break;
}
}
}
# 三. 获取内存
需要导入#import <mach/mach.h>
包。
# 1. 手机内存
// 获得手机内存
unsigned long long fileSize = [NSProcessInfo processInfo].physicalMemory;
// 容量转换
NSInteger KB = 1024;
NSInteger MB = KB*KB;
NSInteger GB = MB*
NSString *fileSizeStr = @"";
if (fileSize < 10) {
fileSizeStr = @"0 B";
}else if (fileSize < KB) {
fileSizeStr = @"< 1 KB";
}else if (fileSize < MB) {
fileSizeStr = [NSString stringWithFormat:@"%.1f KB",((CGFloat)fileSize)/KB];
}else if (fileSize < GB) {
fileSizeStr = [NSString stringWithFormat:@"%.1f MB",((CGFloat)fileSize)/MB];
}else {
fileSizeStr = [NSString stringWithFormat:@"%.1f GB",((CGFloat)fileSize)/GB];
}
NSLog(@"%@", fileSizeStr);
# 2. 获取可用内存
// 获取可用内存
unsigned long long usableFileSize = 0;
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){
usableFileSize = NSNotFound;
}
usableFileSize = ((vm_page_size * vmStats.free_count + vm_page_size * vmStats.inactive_count));
// 容量转换
NSInteger KB = 1024;
NSInteger MB = KB*KB;
NSInteger GB = MB*KB;
NSString *usableFileSizeStr = @"";
if (usableFileSize < 10) {
usableFileSizeStr = @"0 B";
}else if (usableFileSize < KB) {
usableFileSizeStr = @"< 1 KB";
}else if (usableFileSize < MB) {
usableFileSizeStr = [NSString stringWithFormat:@"%.1f KB",((CGFloat)usableFileSize)/KB];
}else if (usableFileSize < GB) {
usableFileSizeStr = [NSString stringWithFormat:@"%.1f MB",((CGFloat)usableFileSize)/MB];
}else {
usableFileSizeStr = [NSString stringWithFormat:@"%.1f GB",((CGFloat)usableFileSize)/GB];
}
NSLog(@"%@", usableFileSizeStr);
# 四. 获取设备类型
需要导入:#import <sys/sysctl.h>
包
// 调用
NSString *deviceType = [self getCurrentDeviceModel:self];
//5.获取设备型号
-(NSString *)getCurrentDeviceModel:(UIViewController *)controller
{
int mib[2];
size_t len;
char *machine;
mib[0] = CTL_HW;
mib[1] = HW_MACHINE;
sysctl(mib, 2, NULL, &len, NULL, 0);
machine = malloc(len);
sysctl(mib, 2, machine, &len, NULL, 0);
NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
free(machine);
if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (A1428)";
if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (A1429/A1442)";
if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (A1456/A1532)";
if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (A1507/A1516/A1526/A1529)";
if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (A1453/A1533)";
if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (A1457/A1518/A1528/A1530)";
if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
//添加 7 判断
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 (A1213)";
if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G (A1288)";
if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G (A1318)";
if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G (A1367)";
if ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G (A1421/A1509)";
if ([platform isEqualToString:@"iPad1,1"]) return @"iPad 1G (A1219/A1337)";
if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2 (A1395)";
if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2 (A1396)";
if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2 (A1397)";
if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2 (A1395+New Chip)";
if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini 1G (A1432)";
if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini 1G (A1454)";
if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini 1G (A1455)";
if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3 (A1416)";
if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3 (A1403)";
if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3 (A1430)";
if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4 (A1458)";
if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4 (A1459)";
if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4 (A1460)";
if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air (A1474)";
if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air (A1475)";
if ([platform isEqualToString:@"iPad4,3"]) return @"iPad Air (A1476)";
if ([platform isEqualToString:@"iPad4,4"]) return @"iPad Mini 2G (A1489)";
if ([platform isEqualToString:@"iPad4,5"]) return @"iPad Mini 2G (A1490)";
if ([platform isEqualToString:@"iPad4,6"]) return @"iPad Mini 2G (A1491)";
if ([platform isEqualToString:@"i386"]) return @"iPhone Simulator";
if ([platform isEqualToString:@"x86_64"]) return @"iPhone Simulator";
return platform;
}
# 五. 获取 IP 地址
需要导入下列包:
#import <sys/sysctl.h>//内存
#import <mach/mach.h>
#import <ifaddrs.h> //ip
#import <arpa/inet.h>
#import <net/if.h>
#pragma mark - 获取设备当前网络IP地址 (WiFi 手机流量通用)
- (NSString *)getIPAddressWithPreferIPv4:(BOOL)preferIPv4
{
NSArray *searchArray = preferIPv4 ?
@[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
@[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
NSDictionary *addresses = [self getIPAddresses];
NSLog(@"addresses: %@", addresses);
__block NSString *address;
[searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
{
address = addresses[key];
//筛选出IP地址格式
if([self isValidatIP:address]) *stop = YES;
} ];
return address ? address : @"0.0.0.0";
}
- (BOOL)isValidatIP:(NSString *)ipAddress {
if (ipAddress.length == 0) {
return NO;
}
NSString *urlRegEx = @"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];
if (regex != nil) {
NSTextCheckingResult *firstMatch=[regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];
if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:0];
NSString *result=[ipAddress substringWithRange:resultRange];
//输出结果
NSLog(@"%@",result);
return YES;
}
}
return NO;
}
- (NSDictionary *)getIPAddresses
{
NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
// retrieve the current interfaces - returns 0 on success
struct ifaddrs *interfaces;
if(!getifaddrs(&interfaces)) {
// Loop through linked list of interfaces
struct ifaddrs *interface;
for(interface=interfaces; interface; interface=interface->ifa_next) {
if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
continue; // deeply nested code harder to read
}
const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
NSString *type;
if(addr->sin_family == AF_INET) {
if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
type = IP_ADDR_IPv4;
}
} else {
const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
type = IP_ADDR_IPv6;
}
}
if(type) {
NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
addresses[key] = [NSString stringWithUTF8String:addrBuf];
}
}
}
// Free memory
freeifaddrs(interfaces);
}
return [addresses count] ? addresses : nil;
}
# 六. 获取当前 WiFi 名称
需要导入:#import <SystemConfiguration/CaptiveNetwork.h>
包。
// 当前手机连接的WIFI名称(SSID)
- (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;
wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
CFRelease(dictRef);
}
}
CFRelease(wifiInterfaces);
return wifiName;
}