您的位置:首页 > 移动开发 > IOS开发

获取各种设备信息,整理

2015-06-04 17:17 459 查看
#pragma mark 获得程序 所有进程//返回所有正在运行的进程的 id,name,占用cpu,运行时间 包含头文件:#include <sys/sysctl.h>//使用函数int sysctl(int *, u_int, void *, size_t *, void *, size_t)+ (NSArray *)runningProcesses{ //指定名字参数,按照顺序第一个元素指定本请求定向到内核的哪个子系统,第二个及其后元素依次细化指定该系统的某个部分。 //CTL_KERN,KERN_PROC,KERN_PROC_ALL 正在运行的所有进程 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL ,0}; size_t miblen = 4; //值-结果参数:函数被调用时,size指向的值指定该缓冲区的大小;函数返回时,该值给出内核存放在该缓冲区中的数据量 //如果这个缓冲不够大,函数就返回ENOMEM错误 size_t size; //返回0,成功;返回-1,失败 int st = sysctl(mib, miblen, NULL, &size, NULL, 0); struct kinfo_proc * process = NULL; struct kinfo_proc * newprocess = NULL; do { size += size / 10; newprocess = realloc(process, size); if (!newprocess) { if (process) { free(process); process = NULL; } return nil; } process = newprocess; st = sysctl(mib, miblen, process, &size, NULL, 0); } while (st == -1 && errno == ENOMEM); if (st == 0) { if (size % sizeof(struct kinfo_proc) == 0) { int nprocess = size / sizeof(struct kinfo_proc); if (nprocess) { NSMutableArray * array = [[NSMutableArray alloc] init]; for (int i = nprocess - 1; i >= 0; i--) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid]; NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm]; NSString * proc_CPU = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_estcpu]; double t = [[NSDate date] timeIntervalSince1970] - process[i].kp_proc.p_un.__p_starttime.tv_sec; NSString * proc_useTiem = [[NSString alloc] initWithFormat:@"%d",(int)t]; NSString *startTime = [[NSString alloc] initWithFormat:@"%ld", process[i].kp_proc.p_un.__p_starttime.tv_sec]; NSString * status = [[NSString alloc] initWithFormat:@"%d",process[i].kp_proc.p_flag]; NSMutableDictionary *dic = [[NSMutableDictionary alloc] init]; // [dic setValue:processID forKey:@"ProcessID"]; [dic setValue:processName forKey:@"ProcessName"]; // [dic setValue:proc_CPU forKey:@"ProcessCPU"]; [dic setValue:proc_useTiem forKey:@"ProcessUseTime"]; // [dic setValue:startTime forKey:@"startTime"]; // 18432 is the currently running application // 16384 is background // [dic setValue:status forKey:@"status"]; [processID release]; [processName release]; [proc_CPU release]; [proc_useTiem release]; [array addObject:dic]; [startTime release]; [status release]; [dic release]; [pool release]; } free(process); process = NULL; //NSLog(@"array = %@",array); return array; } } } return nil;}
#pragma mark//- (void)getResults//{// @autoreleasepool// {// // // NSArray* array = [self runningProcesses];// // XLog(@"array = %@",array);// // // NSString* strUrl = [NSString stringWithFormat:@"%@&%@&%@&%d&%@",// // @"6D8CBA2B-4DC1-4B5E-A54B-1B4B3899141E",// // @"AAAC1C9B-3436-4508-B85A-AA5AEAB3302A",@"2384b698dbf8f083474cdbc440763c769147fae3",[AppDelegate t1],task_id];// // NSString* strUrl = [NSString stringWithFormat:@"%@&%@&%@&%d&%@",// [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString],// [[[UIDevice currentDevice] identifierForVendor] UUIDString],// [OpenUDID value],// [AppDelegate t1],// task_id];// // NSString* dDES = [DesUtil encryptUseDES:strUrl key:@"ituidong"];// // NSString* strWebSafeString = [dDES stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];// // // NSString* strRealUrl = [NSString stringWithFormat:@"%@jfindex/getprocess/?param=%@",BASE_URL,// strWebSafeString];// // // FILE* fp = fopen("/User/url_param.txt","wb");// // fwrite([strRealUrl UTF8String], strlen([strRealUrl UTF8String]), 1, fp);// // fclose(fp);// // NSURL* u = [NSURL URLWithString:strRealUrl];// // NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:u];// // [request setHTTPMethod:@"POST"];// // NSString* strJson = [[NSString alloc] initWithData:[self toJSONData:array] encoding:NSUTF8StringEncoding];// XLog(@"strJson = %@",strJson);// NSString* strJson1 = [DesUtil encryptUseDES:strJson key:@"ituidong"];// // XLog(@"strJson1 = %@",strJson1);// NSString* strDJson = [strJson1 stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];// // // fp = fopen("/User/url_body.txt","wb");// // fwrite([strDJson UTF8String], strlen([strDJson UTF8String]), 1, fp);// // fclose(fp);// // XLog(@"strDJson = %@",strDJson);// // // [request setHTTPBody:[strDJson dataUsingEncoding:NSUTF8StringEncoding]];// // // // [NSURLConnection sendSynchronousRequest:request returningResponse:0 error:0];// // // [strJson release];// [array release];// }//}

#pragma mark 获取设备信息- (void) showDeviceInfo{ UIDevice* myDevice = [UIDevice currentDevice]; NSLog(@"设备名称 - %@", myDevice.name); NSLog(@"设备模式 - %@", myDevice.model); NSLog(@"设备本地模式 - %@", myDevice.localizedModel); NSLog(@"系统名称 - %@", myDevice.systemName); NSLog(@"系统版本 - %@", myDevice.systemVersion); // typedef NS_ENUM(NSInteger, UIDeviceOrientation) { // UIDeviceOrientationUnknown, // UIDeviceOrientationPortrait, // Device oriented vertically, home button on the bottom // UIDeviceOrientationPortraitUpsideDown, // Device oriented vertically, home button on the top // UIDeviceOrientationLandscapeLeft, // Device oriented horizontally, home button on the right // UIDeviceOrientationLandscapeRight, // Device oriented horizontally, home button on the left // UIDeviceOrientationFaceUp, // Device oriented flat, face up // UIDeviceOrientationFaceDown // Device oriented flat, face down // }; NSLog(@"设备朝向 - %d", myDevice.orientation); // 详见UIDeviceOrientation NSLog(@"设备UUID - %@", myDevice.identifierForVendor); // 当前设备是否有转向通知 NSLog(@"设备转向通知(BOOL) - %hhd", myDevice.generatesDeviceOrientationNotifications); // 是否启动电池监控,默认为NO NSLog(@"电池监控启用状态(BOOL) - %hhd", myDevice.batteryMonitoringEnabled); // typedef NS_ENUM(NSInteger, UIDeviceBatteryState) { // UIDeviceBatteryStateUnknown, // UIDeviceBatteryStateUnplugged, // on battery, discharging // UIDeviceBatteryStateCharging, // plugged in, less than 100% // UIDeviceBatteryStateFull, // plugged in, at 100% // }; // available in iPhone 3.0 NSLog(@"电池状态 - %d", myDevice.batteryState); // 详见UIDeviceBatteryState // 电量百分比, 0到1.0,如果电池状态为UIDeviceBatteryStateUnknown,则百分比为-1.0 NSLog(@"电池电量 - %f", myDevice.batteryLevel); // 是否启动接近监控(比如脸接近手机屏),默认为NO NSLog(@"接近监控启用状态(BOOL) - %hhd", myDevice.proximityMonitoringEnabled); // 如果没有接近感应器,则返回NO NSLog(@"接近状态(BOOL) - %hhd", myDevice.proximityState); NSLog(@"是否支持多任务(BOOL) - %hhd", myDevice.multitaskingSupported); // typedef NS_ENUM(NSInteger, UIUserInterfaceIdiom) { // UIUserInterfaceIdiomUnspecified = -1, //#if __IPHONE_3_2 <= __IPHONE_OS_VERSION_MAX_ALLOWED // UIUserInterfaceIdiomPhone, // iPhone and iPod touch style UI // UIUserInterfaceIdiomPad, // iPad style UI //#endif // }; NSLog(@"用户界面模式 - %d", myDevice.userInterfaceIdiom); // 详见UIUserInterfaceIdiom}
#pragma mark MAC addy// Return the local MAC addy// Courtesy of FreeBSD hackers email list// Accidentally munged during previous update. Fixed thanks to mlamb.- (NSString *) macaddress{ int mib[6]; size_t len; char *buf; unsigned char *ptr; struct if_msghdr *ifm; struct sockaddr_dl *sdl; mib[0] = CTL_NET; mib[1] = AF_ROUTE; mib[2] = 0; mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; if ((mib[5] = if_nametoindex("en0")) == 0) { printf("Error: if_nametoindex error/n"); return NULL; } if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { printf("Error: sysctl, take 1/n"); return NULL; } if ((buf = malloc(len)) == NULL) { printf("Could not allocate memory. error!/n"); return NULL; } if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { printf("Error: sysctl, take 2"); return NULL; } ifm = (struct if_msghdr *)buf; sdl = (struct sockaddr_dl *)(ifm + 1); ptr = (unsigned char *)LLADDR(sdl); // NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)]; NSString *outstring = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)]; free(buf); return [outstring uppercaseString];}
#pragma mark 获取 IP 地址//获取ip地址的代码有很多
//这是外网可见的ip地址,如果你在小区的局域网中,那就是小区的,不是局域网的内网地址。- (NSString *) whatismyipdotcom{ NSError *error; NSURL *ipURL = [NSURL URLWithString:@"http://www.whatismyip.com/automation/n09230945.asp"]; NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:1 error:&error]; return ip ? ip : [error localizedDescription];}
//这是获取本地wifi的ip地址
// Matt Brown's get WiFi IP addy solution// Author gave permission to use in Cookbook under cookbook license// http://mattbsoftware.blogspot.com/2009/04/how-to-get-ip-address-of-iphone-os-v221.html- (NSString *) localWiFiIPAddress{ BOOL success; struct ifaddrs * addrs; const struct ifaddrs * cursor; success = getifaddrs(&addrs) == 0; if (success) { cursor = addrs; while (cursor != NULL) { // the second test keeps from picking up the loopback address if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0) { NSString *name = [NSString stringWithUTF8String:cursor->ifa_name]; if ([name isEqualToString:@"en0"]) // Wi-Fi adapter return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)]; } cursor = cursor->ifa_next; } freeifaddrs(addrs); } return nil;}
//NSString和Address的转换+ (NSString *) stringFromAddress: (const struct sockaddr *) address{ if(address && address->sa_family == AF_INET) { const struct sockaddr_in* sin = (struct sockaddr_in*) address; return [NSString stringWithFormat:@"%@:%d", [NSString stringWithUTF8String:inet_ntoa(sin->sin_addr)], ntohs(sin->sin_port)]; } return nil;}
+ (BOOL)addressFromString:(NSString *)IPAddress address:(struct sockaddr_in *)address{ if (!IPAddress || ![IPAddress length]) { return NO; } memset((char *) address, sizeof(struct sockaddr_in), 0); address->sin_family = AF_INET; address->sin_len = sizeof(struct sockaddr_in); int conversionResult = inet_aton([IPAddress UTF8String], &address->sin_addr); if (conversionResult == 0) { NSAssert1(conversionResult != 1, @"Failed to convert the IP address string into a sockaddr_in: %@", IPAddress); return NO; } return YES;}//获取host的名称- (NSString *) hostname{ char baseHostName[256]; // Thanks, Gunnar Larisch int success = gethostname(baseHostName, 255); if (success != 0) return nil; baseHostName[255] = '/0'; #if TARGET_IPHONE_SIMULATOR return [NSString stringWithFormat:@"%s", baseHostName];#else return [NSString stringWithFormat:@"%s.local", baseHostName];#endif}//从host获取地址- (NSString *) getIPAddressForHost: (NSString *) theHost{ struct hostent *host = gethostbyname([theHost UTF8String]); if (!host) {herror("resolv"); return NULL; } struct in_addr **list = (struct in_addr **)host->h_addr_list; NSString *addressString = [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding]; return addressString;}//这是本地host的IP地址- (NSString *) localIPAddress{ struct hostent *host = gethostbyname([[self hostname] UTF8String]); if (!host) {herror("resolv"); return nil;} struct in_addr **list = (struct in_addr **)host->h_addr_list; return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];}
#pragma mark 开发之获取系统磁盘大小和可用磁盘大小//NSFileManager包含非常丰富的信息,通过下面的方法可很容易的获取系统磁盘的大小和可用磁盘的大小- (NSNumber *) totalDiskSpace{ NSDictionary *fattributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:NSHomeDirectory()]; return [fattributes objectForKey:NSFileSystemSize];}
- (NSNumber *) freeDiskSpace{ NSDictionary *fattributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:NSHomeDirectory()]; return [fattributes objectForKey:NSFileSystemFreeSize];}
//参见NSFileManager的头文件尾部定义的字段,不难发现还有许多可以获取的信息的。//具体的都可以根据需求来获取。//FOUNDATION_EXPORT NSString * const NSFileType;
#pragma mark 获取系统背光灯亮度和设备的IMEI
//这里将介绍如何在iphone下面,通过系统的底层字节获取系统背光灯亮度和设备的IMEI。////这是UIDevice的Catagary,需要手动添加IOKit.frameworks(如果你找不到,那算了)。////代码部分 Thanks Erica Sadun。
////////////////头文件///////////////////////* Erica Sadun, http://ericasadun.com iPhone Developer's Cookbook, 3.0 Edition BSD License, Use at your own risk */
/* http://broadcast.oreilly.com/2009/04/iphone-dev-iokit---the-missing.html In Xcode, I was surprised to see that Apple didn't include IOKit header files. When I tried to add #import <IOKit/IOKit.h>, the file could not be found. So I manually put together a simple header file by hand, added IOKit to my frameworks and attempted to compile. As you can see from the screenshot at the top of this post, I failed to do so. Xcode complained that the IOKit framework could not be found. Despite being filed as public, IOKit is apparently not meant to be used by the general public. As iPhone evangelist Matt Drance tweeted, "IOKit is not public on iPhone. Lack of headers and docs is rarely an oversight." In the official docs, I found a quote that described IOKit as such: "Contains interfaces used by the device. Do not include this framework directly." So in the end, my desire to access that IOKit information was thwarted. For whatever reason, Apple has chosen to list it as a public framework but the reality is that it is not. */#define SUPPORTS_IOKIT_EXTENSIONS 1
/* * To use, you must add the (semi)public IOKit framework before compiling */
//#if SUPPORTS_IOKIT_EXTENSIONS//@interface UIDevice (IOKit_Extensions)//- (NSString *) imei;//- (NSString *) serialnumber;//- (NSString *) backlightlevel;//@end//#endif/////////////////实现文件/////////////////////////*// Erica Sadun, http://ericasadun.com// iPhone Developer's Cookbook, 3.0 Edition// BSD License, Use at your own risk// */////#import "UIDevice-IOKitExtensions.h"//#include <sys/types.h>//#include <sys/sysctl.h>//#import <mach/mach_host.h>//#include <netinet/in.h>//#include <arpa/inet.h>//#include <netdb.h>//#include <ifaddrs.h>//#include <sys/socket.h>//#include <net/if.h>//#include <net/if_dl.h>//#include <ifaddrs.h>////#if SUPPORTS_IOKIT_EXTENSIONS//#pragma mark IOKit miniheaders////#define kIODeviceTreePlane "IODeviceTree"////enum {// kIORegistryIterateRecursively = 0x00000001,// kIORegistryIterateParents = 0x00000002//};////typedef mach_port_t io_object_t;//typedef io_object_t io_registry_entry_t;//typedef char io_name_t[128];//typedef UInt32 IOOptionBits;////CFTypeRef//IORegistryEntrySearchCFProperty(// io_registry_entry_t entry,// const io_name_t plane,// CFStringRef key,// CFAllocatorRef allocator,// IOOptionBits options );////kern_return_t//IOMasterPort( mach_port_t bootstrapPort,// mach_port_t * masterPort );////io_registry_entry_t//IORegistryGetRootEntry(// mach_port_t masterPort );////CFTypeRef//IORegistryEntrySearchCFProperty(// io_registry_entry_t entry,// const io_name_t plane,// CFStringRef key,// CFAllocatorRef allocator,// IOOptionBits options );////kern_return_t mach_port_deallocate//(ipc_space_t task,// mach_port_name_t name);//////@implementation UIDevice (IOKit_Extensions)//#pragma mark IOKit Utils//NSArray *getValue(NSString *iosearch)//{// mach_port_t masterPort;// CFTypeID propID = (CFTypeID) NULL;// unsigned int bufSize;// // kern_return_t kr = IOMasterPort(MACH_PORT_NULL, &masterPort);// if (kr != noErr) return nil;// // io_registry_entry_t entry = IORegistryGetRootEntry(masterPort);// if (entry == MACH_PORT_NULL) return nil;// // CFTypeRef prop = IORegistryEntrySearchCFProperty(entry, kIODeviceTreePlane, (CFStringRef) iosearch, nil, kIORegistryIterateRecursively);// if (!prop) return nil;// // propID = CFGetTypeID(prop);// if (!(propID == CFDataGetTypeID()))// {// mach_port_deallocate(mach_task_self(), masterPort);// return nil;// }// // CFDataRef propData = (CFDataRef) prop;// if (!propData) return nil;// // bufSize = CFDataGetLength(propData);// if (!bufSize) return nil;// // NSString *p1 = [[[NSString alloc] initWithBytes:CFDataGetBytePtr(propData) length:bufSize encoding:1] autorelease];// mach_port_deallocate(mach_task_self(), masterPort);// return [p1 componentsSeparatedByString:@"/0"];//}////- (NSString *) imei//{// NSArray *results = getValue(@"device-imei");// if (results) return [results objectAtIndex:0];// return nil;//}////- (NSString *) serialnumber//{// NSArray *results = getValue(@"serial-number");// if (results) return [results objectAtIndex:0];// return nil;//}////- (NSString *) backlightlevel//{// NSArray *results = getValue(@"backlight-level");// if (results) return [results objectAtIndex:0];// return nil;//}//@end//#endif
#pragma mark 获取系统背光灯亮度+ (float)getBacklightLevel{ //以下方法据查只在2.x的sdk有效,真机测试确实没有效果。 float previousBacklightLevel = 2.0; NSNumber *bl = (NSNumber*) CFPreferencesCopyAppValue(CFSTR("SBBacklightLevel" ), CFSTR("com.apple.springboard")); previousBacklightLevel = [bl floatValue]; //a variable to store the previous level so you can reset it. [bl release]; return previousBacklightLevel;}
//使用上述功能前,需要进入GraphicsServices.h。//因为是私有API,GSEventSetBacklightLevel(float value)这个方法,//可能需要自己额外在GraphicsServices.h里定义一下(有待验证),或者使用ToolChain编译。//一般,会涉及到调节屏幕亮度的程序,都会搭配防止休眠的功能,代码很简单://[[UIApplication sharedApplication] setIdleTimerDisabled:YES];//GSEventSetBacklightLevel(newLevel); //The new level: 0.0 - 1.0.
#pragma mark 获取系统字体
+ (NSArray*)getAllSystemFonts;{ NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease]; NSArray* familys = [UIFont familyNames]; for (id obj in familys) { NSArray* fonts = [UIFont fontNamesForFamilyName:obj]; for (id font in fonts) { [array addObject:font]; } } return array;}
+ (UIFont*)getCurrentFont{ //判断系统字体的size,返回使用的字体。 UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]]; return font;}
#pragma mark
//通过调用这个函数可以出发iphone的振动效果,只是短振+ (void)startVibrate { AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);}//据说可以获取iphone上的用户电话号,当然前提是用户有设置,但是不知为什么,测试无效+ (NSString*)getPhoneNumber{ NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"]; NSLog(@"Phone Number: %@", num); return num;}
#pragma mark
//在获取和系统相关的硬件信息的时候,api的接口有时并不是很多。但是我的理解是iOS终究是一个操作系统,是一个基于unix的衍生系统,从操作系统的角度来理解的话,系统底层的东西是很丰富的。//内核 sysctl 含义详解://l compat子树:内核二进制兼容相关的控制//l debug子树:内核调试与信息查询//l dev子树:用于遍历和查询系统中的设备信息//l hw子树:硬件驱动信息及行为控制//l kern子树:内核核心信息及行为控制//l kstat子树:内核统计数据//l machdep子树:平台相关的行为控制//l net子树:网络子系统//l p1003_1b子树:POSIX 1003.1b 实时扩展行为控制//l security子树:内核安全特性行为控制//l user子树:用户环境配置//l vfs子树:虚拟文件系统信息和行为控制//l vm子树:虚拟内存子系统统计数据和行为控制//l 通过 sysctl 进行调优。
//这样子通过下面的方式,可以得到很多的信息,包括CPU,内存大小等信息:+ (NSString *) getSysInfoByName:(char *)typeSpecifier{ size_t size; sysctlbyname(typeSpecifier, NULL, &size, NULL, 0); char *answer = malloc(size); sysctlbyname(typeSpecifier, answer, &size, NULL, 0); NSString *results = [NSString stringWithCString:answer encoding: NSUTF8StringEncoding]; free(answer); return results;}#pragma mark 获取平台信息+ (NSString *) platform{ return [self getSysInfoByName:"hw.machine"];}+ (NSUInteger) getSysInfo: (uint) typeSpecifier{ size_t size = sizeof(int); int results; int mib[2] = {CTL_HW, typeSpecifier}; sysctl(mib, 2, &results, &size, NULL, 0); return (NSUInteger) results;}#pragma mark 获取CPU频率+ (NSUInteger) getCpuFrequency{ return [self getSysInfo:HW_CPU_FREQ];}#pragma mark 获取总线频率+ (NSUInteger) getBusFrequency{ return [self getSysInfo:HW_BUS_FREQ];}#pragma mark 获取总的内存大小+ (NSUInteger) getTotalMemory{ return [self getSysInfo:HW_PHYSMEM];}#pragma mark 获取用户内存+ (NSUInteger) getUserMemory{ return [self getSysInfo:HW_USERMEM];}#pragma mark 获取socketBufferSize+ (NSUInteger) maxSocketBufferSize{ return [self getSysInfo:KIPC_MAXSOCKBUF];}#pragma mark iphone下获取可用的内存大小+ (NSUInteger)getAvailableMemory{ 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;}
#pragma mark 获取IMSI判断运营商//IMSI 共有 15 位,其结构如下://   MCC+MNC+MSIN ,( MNC+MSIN=NMSI )//   MCC : Mobile Country Code ,移动国家码, MCC 的资源由国际电联( ITU )统一分配和管理,唯一识别移动用户所属的国家,共 3 位,中国为 460;//   MNC:Mobile Network Code ,移动网络码,共 2 位,中国移动 TD 系统使用 00 ,中国联通 GSM 系统使用 01 ,中国移动 GSM 系统使用 02 ,中国电信 CDMA 系统使用 03 ,一个典型的 IMSI 号码为 460030912121001;//   MSIN:Mobile Subscriber Identification Number 共有 10 位,其结构如下://   09+M0M1M2M3+ABCD//其中的 M0M1M2M3 和 MDN 号码中的 H0H1H2H3 可存在对应关系, ABCD 四位为自由分配。//这样就可以依据 IMSI 中的 MCC 和 MNC 来确定运营商了。当然知道编码规则同时还是需要知道对应编码的的国家和网络了。//////实现的代码如下:/* China - CN * MCC MNC Brand Operator Status Bands (MHz) References and notes * 460 00 China Mobile Operational GSM 900/GSM 1800 UMTS (TD-SCDMA) 1880/2010 * 460 01 China Unicom Operational GSM 900/GSM 1800/ UMTS 2100 CDMA network sold to China Telecom, WCDMA commercial trial started in May 2009 and in full commercial operation as of October 2009. * 460 02 China Mobile Operational GSM 900/GSM 1800/ UMTS (TD-SCDMA) 1880/2010 * 460 03 China Telecom Operational CDMA 800/cdma evdo 2100 * 460 05 China Telecom Operational * 460 06 China Unicom Operational GSM 900/GSM 1800/UMTS 2100 * 460 07 China Mobile Operational GSM 900/GSM 1800/UMTS (TD-SCDMA) 1880/2010 * 460 20 China Tietong Operational GSM-R * NA NA China Telecom&China Unicom Operational */+ (NSString*)getCarrier:(NSString*)imsi{ if (imsi == nil || [imsi isEqualToString:@"SIM Not Inserted"] ) { return @"Unknown"; } else { if ([[imsi substringWithRange:NSMakeRange(0, 3)] isEqualToString:@"460"]) { NSInteger MNC = [[imsi substringWithRange:NSMakeRange(3, 2)] intValue]; switch (MNC) { case 00: case 02: case 07: return @"China Mobile"; break; case 01: case 06: return @"China Unicom"; break; case 03: case 05: return @"China Telecom"; break; case 20: return @"China Tietong"; break; default: break; } } } return @"Unknown";}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息