IOS 获取,如电量,CPU,型号等

电池信息可以从UIDevice batteryLevel得到,但是只能精确到0.05.
- (NSDictionary*)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;
}

这个可以精确到0.01,但是好像与系统显示的仍有偏差。



得到平台号:
- (NSString*) doDevicePlatform
{
    size_t size;
    int nR = sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = (char *)malloc(size);
    nR = sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    return platform;
}
在根据平台号得到手机型号:
比如:

   if ([platform isEqualToString:@"iPhone1,1"])
    {
        return @"iPhone";
    }
    if ([platform isEqualToString:@"iPhone1,2"])
    {
        return @"iPhone3G";
    }
    if ([platform isEqualToString:@"iPhone2,1"])
    {
        return @"iPhone3GS";
    }
    if ([platform isEqualToString:@"iPhone3,1"])
    {
        return @"iPhone4";
    } 



得到mac地址:

- (void)printmacinfo
{
        bool success;
        struct ifaddrs *addrs;
        const struct ifaddrs *cursor;
        const struct sockaddr_dl *dlAddr;
        const uint8_t *base;
        
        success = getifaddrs(&addrs) == 0;
        if (success)
        {
                cursor = addrs;
                NSInteger idx = 0;
                while (cursor != NULL)
                {
                        ++idx;
                        NSString* macTitle = nil;
                        if ((cursor->ifa_flags & IFF_LOOPBACK) == 0 )
                        {
                                char* ifaname = (char *)cursor->ifa_name;
                                char* addr = inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr);
                                printf("%s ", ifaname);
                                printf("%s\n", addr);
//                                NSString* tmpstr1 = [NSString stringWithCString:ifaname encoding:NSUTF8StringEncoding];
//                                NSString* tmpstr2 = [NSString stringWithCString:addr encoding:NSUTF8StringEncoding];
//                                NSString *tmpStr = [NSString stringWithFormat:@"%@ %@", tmpstr1, tmpstr2];
                                
                                macTitle = [NSString stringWithFormat:@"%d %s %s", idx, ifaname, addr];
                                
                                [_arrKey addObject:macTitle];
                        }
                        if ( (cursor->ifa_addr->sa_family == AF_LINK)
                                && (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type ==IFT_ETHER)
                                )
                        {
                                dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
                                // fprintf(stderr, " sdl_nlen = %d\n", dlAddr->sdl_nlen);
                                // fprintf(stderr, " sdl_alen = %d\n", dlAddr->sdl_alen);
                                base = (const uint8_t *) &dlAddr->sdl_data[dlAddr->sdl_nlen];
                                printf(" MAC address ");
                                NSMutableString* tmpString = [[[NSMutableString alloc] initWithString:@"Mac:"] autorelease];
                                for (int i = 0; i < dlAddr->sdl_alen; i++)
                                {
                                        if (i != 0)
                                        {
                                                printf(":");
                                                [tmpString appendString:@":"];
                                        }
                                        printf("%02x", base[i]);
                                        [tmpString appendFormat:@"%02X", base[i]];
                                } 
                                printf("\n");
                                [_dic setObject:tmpString forKey:macTitle];
                        }
                        else if (macTitle != nil)
                        {
                                [_dic setObject:@"" forKey:macTitle];
                        }
                        cursor = cursor->ifa_next;
                }
        }
}



得到4种内存信息:

        mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
        vm_statistics_data_t vmstat;
        if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat, &count) != KERN_SUCCESS)
        {
                NSLog(@"Failed to get VM statistics.");
                [_dic setObject:@"Failed to get VM statistics." forKey:KTTMemorySize_Wire];
        }
        else
        {
                float total = vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.free_count;
                float wired = vmstat.wire_count / total * 100;
                float active = vmstat.active_count / total * 100;
                float inactive = vmstat.inactive_count / total * 100;
                float free = vmstat.free_count / total * 100;
//                NSString *str = [NSString stringWithFormat:@"%d %d %d %d %.2f %.2f %.2f %.2f %.0f %.0f"
//                                                 , vmstat.wire_count, vmstat.active_count, vmstat.inactive_count, vmstat.free_count
//                                                 , wired, active, inactive, free
//                                                 , total, total * pageSize
//                                                 ];

        }





cpu和总线频率:
        int result;
        mib[0] = CTL_HW;
        mib[1] = HW_CPU_FREQ;
        length = sizeof(result);
        if (sysctl(mib, 2, &result, &length, NULL, 0) < 0)
        {
                perror("getting cpu frequency");
        }
        printf("CPU Frequency = %u hz\n", result);
        
        int result2;
        mib[0] = CTL_HW;
        mib[1] = HW_BUS_FREQ;
        length = sizeof(result2);
        if (sysctl(mib, 2, &result2, &length, NULL, 0) < 0)
        {
                perror("getting bus frequency");
        }
        printf("Bus Frequency = %u hz\n", result);



网络方面使用的苹果列子文档中的Reachability.h和Reachability.m
外部ip访问http://automation.whatismyip.com/n09230945.asp即可知道。
gethostbyname可知内部局域网ip。



 NetworkStatus netstatus = [reachable currentReachabilityStatus];
    switch (netstatus)
        {
                case NotReachable:
                        // 没有网络连接
                        reachableStatus = NSLocalizedString(@"No Network", "");
                        break;
                case ReachableViaWWAN:
                        // 使用3G网络
                        reachableStatus = @"GPRS/3G";
                        break;
                case ReachableViaWiFi:
                        // 使用WiFi网络
                        reachableStatus = @"WIFI";
                        break;
    }
这个可知网络类型。



内存大小:

    size_t size = sizeof(int);
    int results;
    int mib[2] = {CTL_HW, HW_PHYSMEM};
    sysctl(mib, 2, &results, &size, NULL, 0);




总磁盘大小:
NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
[fattributes objectForKey:NSFileSystemSize];

剩余空间:
[fattributes objectForKey:NSFileSystemFreeSize];




手机号码:
这个也是undocument api
NSString* phoneNumber = CTSettingCopyMyPhoneNumber();





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);
                CFRelease(prop);
                return nil;
        }
        
    CFDataRef propData = (CFDataRef) prop;
    if (!propData)
        {
                CFRelease(prop);
                return nil;
        }
        
    bufSize = CFDataGetLength(propData);
    if (!bufSize)
        {
                CFRelease(prop);
                return nil;
        }
        
    NSString *p1 = [[[NSString alloc] initWithBytes:CFDataGetBytePtr(propData) length:bufSize encoding:1] autorelease];
    mach_port_deallocate(mach_task_self(), masterPort);
        CFRelease(prop);
    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;
}

分别得到imei,序列号,背光。




2010年开始苹果清理了一批APP Store上的WIFI扫描软件, 缘由语焉不详.

这些WIFI扫描软件使用了苹果的私有函数apple80211.framework

尽管不能合法(指能通过App Store的审核)的获取WIFI列表, 不过我们还是可以获取到当前Wifi连接的信息,比如SSID.

SSID全称Service Set IDentifier, 即Wifi网络的公开名称.

苹果在IOS v4.1+版本上提供了公开的方法来获取该信息.

示范代码如下:

[plain]  view plain copy
  1. #import <SystemConfiguration/CaptiveNetwork.h>  
  2.   
  3. - (id)fetchSSIDInfo  
  4. {  
  5.     NSArray *ifs = (id)CNCopySupportedInterfaces();  
  6.     NSLog(@"%s: Supported interfaces: %@", __func__, ifs);  
  7.     id info = nil;  
  8.     for (NSString *ifnam in ifs) {  
  9.         info = (id)CNCopyCurrentNetworkInfo((CFStringRef)ifnam);  
  10.         NSLog(@"%s: %@ => %@", __func__, ifnam, info);  
  11.         if (info && [info count]) {  
  12.             break;  
  13.         }  
  14.         [info release];  
  15.     }  
  16.     [ifs release];  
  17.     return [info autorelease];  
  18. }  

对于ARC版本, 代码可简化如下:

[plain]  view plain copy
  1. - (id)fetchSSIDInfo {  
  2.      NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();  
  3.      NSLog(@"Supported interfaces: %@", ifs);  
  4.      id info = nil;  
  5.      for (NSString *ifnam in ifs) {  
  6.          info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);  
  7.          NSLog(@"%@ => %@", ifnam, info);  
  8.          if (info && [info count]) { break; }  
  9.      }  
  10.      return info;  
  11. }  

参考链接:

1. http://stackoverflow.com/questions/5198716/iphone-get-ssid-without-private-library

2. http://answers.yahoo.com/question/index?qid=20100529040141AAKd8dO




iOS 取得WIFI的热点名称和MAC地址 

#import <SystemConfiguration/CaptiveNetwork.h>


    NSString *ssid = @"Not Found";

    NSString *macIp = @"Not Found";

    CFArrayRef myArray = CNCopySupportedInterfaces();

    if (myArray != nil) {

        CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));

        if (myDict != nil) {

            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);

            

            ssid = [dict valueForKey:@"SSID"];

            macIp = [dict valueForKey:@"BSSID"];

        }

    }

    UIAlertView *av = [[UIAlertView alloc] initWithTitle:ssid

                                                 message:macIp

                                                delegate:nil

                                       cancelButtonTitle:nil

                                       otherButtonTitles:@"OK", nil];

    [av show];





/*

 iphone获取sim卡信息

 1.加入一个Framework(CoreTelephony.framework).

 2.引入头文件

#import <CoreTelephony/CTTelephonyNetworkInfo.h>

#import <CoreTelephony/CTCarrier.h>

 3.初始化

  

 */

//-----------------------------------

具体demo

//-----------------------------------

#import <UIKit/UIKit.h>

#import <CoreTelephony/CTTelephonyNetworkInfo.h>

#import <CoreTelephony/CTCarrier.h>


@interface RootViewController : UITableViewController

{

    //声明变量

    CTTelephonyNetworkInfo *networkInfo;

}

@end


@implementation RootViewController

- (void)viewDidLoad

{

    [super viewDidLoad];

    self.navigationItem.prompt = @"CTTelephonyNetworkInfo";

    self.navigationItem.title = @"CTCarrier";

   

    //初始化

    networkInfo = [[CTTelephonyNetworkInfo allocinit];

    //sim卡更换时弹出此窗口

    networkInfo.subscriberCellularProviderDidUpdateNotifier = ^(CTCarrier *carrier){

        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"Sim card changed" delegate:nilcancelButtonTitle:@"Dismiss" otherButtonTitles:nil];

        [alert show];

        

    };

        

}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    //获取sim卡信息

    CTCarrier *carrier = networkInfo.subscriberCellularProvider;

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:CellIdentifier];

    }

    

    switch (indexPath.row) {

        case 0://供应商名称(中国联通 中国移动)

            cell.textLabel.text = @"carrierName";

            cell.detailTextLabel.text = carrier.carrierName;

            break;

        case 1://所在国家编号

            cell.textLabel.text = @"mobileCountryCode";

            cell.detailTextLabel.text = carrier.mobileCountryCode;

            break;

        case 2://供应商网络编号

            cell.textLabel.text = @"mobileNetworkCode";

            cell.detailTextLabel.text = carrier.mobileNetworkCode;

            break;

        case 3:

            cell.textLabel.text = @"isoCountryCode";

            cell.detailTextLabel.text = carrier.isoCountryCode;

            break;

        case 4://是否允许voip

            cell.textLabel.text = @"allowsVOIP";

            cell.detailTextLabel.text = carrier.allowsVOIP?@"YES":@"NO";

            break;

            

        default:

            break;

    }

    

    return cell;

}

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在UniApp中,要获取iOS设备的电量信息可以通过uni.getBatteryInfoSync()方法来实现。这个方法会返回一个对象,包含了当前设备的电量相关信息,其中包括电量百分比、是否正在充电等。你可以通过使用该方法获取iOS设备的电量信息并进行相应的处理。但需要注意的是,该方法仅在App端有效,小程序端无法获取电量信息。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Uniapp在IOS系统打包测试流程](https://download.csdn.net/download/qq_37914074/86245128)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [uniapp改变顶部的信号、时间、电池显示颜色](https://blog.csdn.net/li1375603382/article/details/104901386)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [uniapp沉浸式状态栏高度 不同手机状态栏高度问题 『 踩坑记录』](https://blog.csdn.net/qq_47917308/article/details/115267867)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值