美文网首页
SystemServices 库源码分析(获取设备信息)(2)

SystemServices 库源码分析(获取设备信息)(2)

作者: 充满活力的早晨 | 来源:发表于2018-09-13 10:47 被阅读32次

SSHardwareInfo 获取硬件信息

// System Uptime (dd hh mm)
+ (NSString *)systemUptime {
    // Set up the days/hours/minutes
    NSNumber *days, *hours, *minutes;
    
    // Get the info about a process
    NSProcessInfo *processInfo = [NSProcessInfo processInfo];
    // Get the uptime of the system
    NSTimeInterval uptimeInterval = [processInfo systemUptime];
    // Get the calendar
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // Create the Dates
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:(0-uptimeInterval)];
    unsigned int unitFlags = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
    NSDateComponents *components = [calendar components:unitFlags fromDate:date toDate:[NSDate date]  options:0];
    
    // Get the day, hour and minutes
    days = [NSNumber numberWithLong:[components day]];
    hours = [NSNumber numberWithLong:[components hour]];
    minutes = [NSNumber numberWithLong:[components minute]];
    
    // Format the dates
    NSString *uptime = [NSString stringWithFormat:@"%@ %@ %@",
                        [days stringValue],
                        [hours stringValue],
                        [minutes stringValue]];
    
    // Error checking
    if (!uptime) {
        // No uptime found
        // Return nil
        return nil;
    }
    
    // Return the uptime
    return uptime;
}

获取系统更新时间 已经更新了多少天,多少小时,多少秒

// Model of Device
+ (NSString *)deviceModel {
    // Get the device model
    if ([[UIDevice currentDevice] respondsToSelector:@selector(model)]) {
        // Make a string for the device model
        NSString *deviceModel = [[UIDevice currentDevice] model];
        // Set the output to the device model
        return deviceModel;
    } else {
        // Device model not found
        return nil;
    }
}

获取是什么设备 ,eg Iphone ,iPod

// Device Name
+ (NSString *)deviceName {
    // Get the current device name
    if ([[UIDevice currentDevice] respondsToSelector:@selector(name)]) {
        // Make a string for the device name
        NSString *deviceName = [[UIDevice currentDevice] name];
        // Set the output to the device name
        return deviceName;
    } else {
        // Device name not found
        return nil;
    }
}

获取设备name 。这个是我们自己取的

// System Name
+ (NSString *)systemName {
    // Get the current system name
    if ([[UIDevice currentDevice] respondsToSelector:@selector(systemName)]) {
        // Make a string for the system name
        NSString *systemName = [[UIDevice currentDevice] systemName];
        // Set the output to the system name
        return systemName;
    } else {
        // System name not found
        return nil;
    }
}

获取系统名字 比如“iOS”

// System Version
+ (NSString *)systemVersion {
    // Get the current system version
    if ([[UIDevice currentDevice] respondsToSelector:@selector(systemVersion)]) {
        // Make a string for the system version
        NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
        // Set the output to the system version
        return systemVersion;
    } else {
        // System version not found
        return nil;
    }
}

获取系统版本 eg:11.3


// System Device Type (iPhone1,0) (Formatted = iPhone 1)
+ (NSString *)systemDeviceTypeFormatted:(BOOL)formatted {
    // Set up a Device Type String
    NSString *deviceType;
    
    // Check if it should be formatted
    if (formatted) {
        // Formatted
        @try {
            // Set up a new Device Type String
            NSString *newDeviceType;
            // Set up a struct
            struct utsname dt;
            // Get the system information
            uname(&dt);
            // Set the device type to the machine type
            deviceType = [NSString stringWithFormat:@"%s", dt.machine];
            
            // Simulators
            if ([deviceType isEqualToString:@"i386"])
                newDeviceType = @"iPhone Simulator";
            else if ([deviceType isEqualToString:@"x86_64"])
                newDeviceType = @"iPhone Simulator";
            // iPhones
            else if ([deviceType isEqualToString:@"iPhone1,1"])
                newDeviceType = @"iPhone";
            else if ([deviceType isEqualToString:@"iPhone1,2"])
                newDeviceType = @"iPhone 3G";
            else if ([deviceType isEqualToString:@"iPhone2,1"])
                newDeviceType = @"iPhone 3GS";
            else if ([deviceType isEqualToString:@"iPhone3,1"])
                newDeviceType = @"iPhone 4";
            else if ([deviceType isEqualToString:@"iPhone4,1"])
                newDeviceType = @"iPhone 4S";
            else if ([deviceType isEqualToString:@"iPhone5,1"])
                newDeviceType = @"iPhone 5 (GSM)";
            else if ([deviceType isEqualToString:@"iPhone5,2"])
                newDeviceType = @"iPhone 5 (GSM+CDMA)";
            else if ([deviceType isEqualToString:@"iPhone5,3"])
                newDeviceType = @"iPhone 5c (GSM)";
            else if ([deviceType isEqualToString:@"iPhone5,4"])
                newDeviceType = @"iPhone 5c (GSM+CDMA)";
            else if ([deviceType isEqualToString:@"iPhone6,1"])
                newDeviceType = @"iPhone 5s (GSM)";
            else if ([deviceType isEqualToString:@"iPhone6,2"])
                newDeviceType = @"iPhone 5s (GSM+CDMA)";
            else if ([deviceType isEqualToString:@"iPhone7,1"])
                newDeviceType = @"iPhone 6 Plus";
            else if ([deviceType isEqualToString:@"iPhone7,2"])
                newDeviceType = @"iPhone 6";
            else if ([deviceType isEqualToString:@"iPhone8,1"])
                newDeviceType = @"iPhone 6s";
            else if ([deviceType isEqualToString:@"iPhone8,2"])
                newDeviceType = @"iPhone 6s Plus";
            else if ([deviceType isEqualToString:@"iPhone8,4"])
                newDeviceType = @"iPhone SE";
            else if ([deviceType isEqualToString:@"iPhone9,1"])
                newDeviceType = @"iPhone 7 (CDMA+GSM/LTE)";
            else if ([deviceType isEqualToString:@"iPhone9,3"])
                newDeviceType = @"iPhone 7 (GSM/LTE)";
            else if ([deviceType isEqualToString:@"iPhone9,2"])
                newDeviceType = @"iPhone 7 Plus (CDMA+GSM/LTE)";
            else if ([deviceType isEqualToString:@"iPhone9,4"])
                newDeviceType = @"iPhone 7 Plus (GSM/LTE)";
            else if ([deviceType isEqualToString:@"iPhone10,1"])
                newDeviceType = @"iPhone 8 (CDMA+GSM/LTE)";
            else if ([deviceType isEqualToString:@"iPhone10,4"])
                newDeviceType = @"iPhone 8 (GSM/LTE)";
            else if ([deviceType isEqualToString:@"iPhone10,2"])
                newDeviceType = @"iPhone 8 Plus (CDMA+GSM/LTE)";
            else if ([deviceType isEqualToString:@"iPhone10,5"])
                newDeviceType = @"iPhone 8 Plus (GSM/LTE)";
            else if ([deviceType isEqualToString:@"iPhone10,3"])
                newDeviceType = @"iPhone X (CDMA+GSM/LTE)";
            else if ([deviceType isEqualToString:@"iPhone10,6"])
                newDeviceType = @"iPhone X (GSM/LTE)";
            // iPods
            else if ([deviceType isEqualToString:@"iPod1,1"])
                newDeviceType = @"iPod Touch 1G";
            else if ([deviceType isEqualToString:@"iPod2,1"])
                newDeviceType = @"iPod Touch 2G";
            else if ([deviceType isEqualToString:@"iPod3,1"])
                newDeviceType = @"iPod Touch 3G";
            else if ([deviceType isEqualToString:@"iPod4,1"])
                newDeviceType = @"iPod Touch 4G";
            else if ([deviceType isEqualToString:@"iPod5,1"])
                newDeviceType = @"iPod Touch 5G";
            else if ([deviceType isEqualToString:@"iPod7,1"])
                newDeviceType = @"iPod Touch 6G";
            // iPads
            else if ([deviceType isEqualToString:@"iPad1,1"])
                newDeviceType = @"iPad";
            else if ([deviceType isEqualToString:@"iPad2,1"])
                newDeviceType = @"iPad 2 (WiFi)";
            else if ([deviceType isEqualToString:@"iPad2,2"])
                newDeviceType = @"iPad 2 (GSM)";
            else if ([deviceType isEqualToString:@"iPad2,3"])
                newDeviceType = @"iPad 2 (CDMA)";
            else if ([deviceType isEqualToString:@"iPad2,4"])
                newDeviceType = @"iPad 2 (WiFi + New Chip)";
            else if ([deviceType isEqualToString:@"iPad2,5"])
                newDeviceType = @"iPad mini (WiFi)";
            else if ([deviceType isEqualToString:@"iPad2,6"])
                newDeviceType = @"iPad mini (GSM)";
            else if ([deviceType isEqualToString:@"iPad2,7"])
                newDeviceType = @"iPad mini (GSM+CDMA)";
            else if ([deviceType isEqualToString:@"iPad3,1"])
                newDeviceType = @"iPad 3 (WiFi)";
            else if ([deviceType isEqualToString:@"iPad3,2"])
                newDeviceType = @"iPad 3 (GSM)";
            else if ([deviceType isEqualToString:@"iPad3,3"])
                newDeviceType = @"iPad 3 (GSM+CDMA)";
            else if ([deviceType isEqualToString:@"iPad3,4"])
                newDeviceType = @"iPad 4 (WiFi)";
            else if ([deviceType isEqualToString:@"iPad3,5"])
                newDeviceType = @"iPad 4 (GSM)";
            else if ([deviceType isEqualToString:@"iPad3,6"])
                newDeviceType = @"iPad 4 (GSM+CDMA)";
            else if ([deviceType isEqualToString:@"iPad4,1"])
                newDeviceType = @"iPad Air (WiFi)";
            else if ([deviceType isEqualToString:@"iPad4,2"])
                newDeviceType = @"iPad Air (Cellular)";
            else if ([deviceType isEqualToString:@"iPad4,3"])
                newDeviceType = @"iPad Air (China)";
            else if ([deviceType isEqualToString:@"iPad4,4"])
                newDeviceType = @"iPad mini 2 (WiFi)";
            else if ([deviceType isEqualToString:@"iPad4,5"])
                newDeviceType = @"iPad mini 2 (Cellular)";
            else if ([deviceType isEqualToString:@"iPad5,1"])
                newDeviceType = @"iPad mini 4 (WiFi)";
            else if ([deviceType isEqualToString:@"iPad5,2"])
                newDeviceType = @"iPad mini 4 (Cellular)";
            else if ([deviceType isEqualToString:@"iPad5,4"])
                newDeviceType = @"iPad Air 2 (WiFi)";
            else if ([deviceType isEqualToString:@"iPad5,5"])
                newDeviceType = @"iPad Air 2 (Cellular)";
            else if ([deviceType isEqualToString:@"iPad6,3"])
                newDeviceType = @"9.7-inch iPad Pro (WiFi)";
            else if ([deviceType isEqualToString:@"iPad6,4"])
                newDeviceType = @"9.7-inch iPad Pro (Cellular)";
            else if ([deviceType isEqualToString:@"iPad6,7"])
                newDeviceType = @"12.9-inch iPad Pro (WiFi)";
            else if ([deviceType isEqualToString:@"iPad6,8"])
                newDeviceType = @"12.9-inch iPad Pro (Cellular)";
            else if ([deviceType isEqualToString:@"iPad6,11"])
                newDeviceType = @"iPad 5 (WiFi)";
            else if ([deviceType isEqualToString:@"iPad6,12"])
                newDeviceType = @"iPad 5 (Cellular)";
            else if ([deviceType isEqualToString:@"iPad7,1"])
                newDeviceType = @"iPad Pro 12.9 (2nd Gen - WiFi)";
            else if ([deviceType isEqualToString:@"iPad7,2"])
                newDeviceType = @"iPad Pro 12.9 (2nd Gen - Cellular)";
            else if ([deviceType isEqualToString:@"iPad7,3"])
                newDeviceType = @"iPad Pro 10.5 (WiFi)";
            else if ([deviceType isEqualToString:@"iPad7,4"])
                newDeviceType = @"iPad Pro 10.5 (Cellular)";
            // Catch All iPad
            else if ([deviceType hasPrefix:@"iPad"])
                newDeviceType = @"iPad";
            // Apple TV
            else if ([deviceType isEqualToString:@"AppleTV2,1"])
                newDeviceType = @"Apple TV 2";
            else if ([deviceType isEqualToString:@"AppleTV3,1"])
                newDeviceType = @"Apple TV 3";
            else if ([deviceType isEqualToString:@"AppleTV3,2"])
                newDeviceType = @"Apple TV 3 (2013)";

            // Return the new device type
            return newDeviceType;
        }
        @catch (NSException *exception) {
            // Error
            return nil;
        }
    } else {
        // Unformatted
        @try {
            // Set up a struct
            struct utsname dt;
            // Get the system information
            uname(&dt);
            // Set the device type to the machine type
            deviceType = [NSString stringWithFormat:@"%s", dt.machine];
            
            // Return the device type
            return deviceType;
        }
        @catch (NSException *exception) {
            // Error
            return nil;
        }
    }
}

获取设备的machine。这随着iphone设备的增多,而增加。要是后台要,让后台给匹配,我们本地不做转换

// Get the Screen Width (X)
+ (NSInteger)screenWidth {
    // Get the screen width
    @try {
        // Screen bounds
        CGRect Rect = [[UIScreen mainScreen] bounds];
        // Find the width (X)
        NSInteger Width = Rect.size.width;
        // Verify validity
        if (Width <= 0) {
            // Invalid Width
            return -1;
        }
        
        // Successful
        return Width;
    }
    @catch (NSException *exception) {
        // Error
        return -1;
    }
}

屏幕宽

// Get the Screen Height (Y)
+ (NSInteger)screenHeight {
    // Get the screen height
    @try {
        // Screen bounds
        CGRect Rect = [[UIScreen mainScreen] bounds];
        // Find the Height (Y)
        NSInteger Height = Rect.size.height;
        // Verify validity
        if (Height <= 0) {
            // Invalid Height
            return -1;
        }
        
        // Successful
        return Height;
    }
    @catch (NSException *exception) {
        // Error
        return -1;
    }
}

屏幕高

// Get the Screen Brightness
+ (float)screenBrightness {
    // Get the screen brightness
    @try {
        // Brightness
        float brightness = [UIScreen mainScreen].brightness;
        // Verify validity
        if (brightness < 0.0 || brightness > 1.0) {
            // Invalid brightness
            return -1;
        }
        
        // Successful
        return (brightness * 100);
    }
    @catch (NSException *exception) {
        // Error
        return -1;
    }
}

获取屏幕的明亮度。 主屏幕

// Multitasking enabled?
+ (BOOL)multitaskingEnabled {
    // Is multitasking enabled?
    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
        // Create a bool
        BOOL MultitaskingSupported = [UIDevice currentDevice].multitaskingSupported;
        // Return the value
        return MultitaskingSupported;
    } else {
        // Doesn't respond to selector
        return false;
    }
}

是否支持多任务

// Proximity sensor enabled?
+ (BOOL)proximitySensorEnabled {
    // Is the proximity sensor enabled?
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setProximityMonitoringEnabled:)]) {
        // Create a UIDevice variable
        UIDevice *device = [UIDevice currentDevice];
        
        // Make a Bool for the proximity Sensor
        BOOL ProximitySensor;
        
        // Turn the sensor on, if not already on, and see if it works
        if (device.proximityMonitoringEnabled != YES) {
            // Sensor is off
            // Turn it on
            [device setProximityMonitoringEnabled:YES];
            // See if it turned on
            if (device.proximityMonitoringEnabled == YES) {
                // It turned on!  Turn it off
                [device setProximityMonitoringEnabled:NO];
                // It works
                ProximitySensor = true;
            } else {
                // Didn't turn on, no good
                ProximitySensor = false;
            }
        } else {
            // Sensor is already on
            ProximitySensor = true;
        }
        
        // Return on or off
        return ProximitySensor;
    } else {
        // Doesn't respond to selector
        return false;
    }
}

是否能开启接近传感器(这个地方有点意思,后期再回来看看)

// Debugging attached?
+ (BOOL)debuggerAttached {
    // Is the debugger attached?
    @try {
        // Set up the variables
        int                 ret;
        int                 mib[4];
        struct kinfo_proc   info;
        size_t              size;
        info.kp_proc.p_flag = 0;
        mib[0] = CTL_KERN;
        mib[1] = KERN_PROC;
        mib[2] = KERN_PROC_PID;
        mib[3] = getpid();
        size = sizeof(info);
        ret = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
        
        // Verify ret
        if (ret) {
            // Sysctl() failed
            // Return the output of sysctl
            return ret;
        }
        
        // Return whether the process is being traced or not
        return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
        
    }
    @catch (NSException *exception) {
        // Error
        return false;
    }
}

是否开启调试模式 。反调试

// Plugged In?
+ (BOOL)pluggedIn {
    // Is the device plugged in?
    if ([[UIDevice currentDevice] respondsToSelector:@selector(batteryState)]) {
        // Create a bool
        BOOL PluggedIn;
        // Set the battery monitoring enabled
        [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
        // Get the battery state
        UIDeviceBatteryState batteryState = [UIDevice currentDevice].batteryState;
        // Check if it's plugged in or finished charging
        if (batteryState == UIDeviceBatteryStateCharging || batteryState == UIDeviceBatteryStateFull) {
            // We're plugged in
            PluggedIn = true;
        } else {
            PluggedIn = false;
        }
        // Return the value
        return PluggedIn;
    } else {
        // Doesn't respond to selector
        return false;
    }
}

检查设备是否再充电。

// Step-Counting Available?
+ (BOOL)stepCountingAvailable {
    @try {
        // Make sure the Pedometer class exists
        if ([CMPedometer class]) {
            // Make sure the selector exists
            if ([CMPedometer respondsToSelector:@selector(isStepCountingAvailable)]) {
                // Return whether it's available
                return [CMPedometer isStepCountingAvailable];
            }
        }
        // Not available
        return false;
    }
    @catch (NSException *exception) {
        // Error
        return false;
    }
}

是否支持获取步数 Healthkit

// Distance Available
+ (BOOL)distanceAvailable {
    @try {
        // Make sure the Pedometer class exists
        if ([CMPedometer class]) {
            // Make sure the selector exists
            if ([CMPedometer respondsToSelector:@selector(isDistanceAvailable)]) {
                // Return whether it's available
                return [CMPedometer isDistanceAvailable];
            }
        }
        // Not available
        return false;
    }
    @catch (NSException *exception) {
        // Error
        return false;
    }
}

获取支持走了多少步

// Floor Counting Available
+ (BOOL)floorCountingAvailable {
    @try {
        // Make sure the Pedometer class exists
        if ([CMPedometer class]) {
            // Make sure the selector exists
            if ([CMPedometer respondsToSelector:@selector(isFloorCountingAvailable)]) {
                // Return whether it's available
                return [CMPedometer isFloorCountingAvailable];
            }
        }
        // Not available
        return false;
    }
    @catch (NSException *exception) {
        // Error
        return false;
    }
}

是否支持楼层高度

SSJailbreakCheck 越狱检测

不太了解越狱暂时不做分析了之贴下代码就行了。

// Is the application running on a jailbroken device?
+ (int)jailbroken {
    // Is the device jailbroken?
    
    // Make an int to monitor how many checks are failed
    int motzart = 0;
    
    // Check if iOS 8 or lower
    if (SYSTEM_VERSION_LESS_THAN(@"9.0")) {
        // URL Check
        if ([self urlCheck] != NOTJAIL) {
            // Jailbroken
            motzart += 3;
        }
    }
    
    // Cydia Check
    if ([self cydiaCheck] != NOTJAIL) {
        // Jailbroken
        motzart += 3;
    }
    
    // Inaccessible Files Check
    if ([self inaccessibleFilesCheck] != NOTJAIL) {
        // Jailbroken
        motzart += 2;
    }
    
    // Plist Check
    if ([self plistCheck] != NOTJAIL) {
        // Jailbroken
        motzart += 2;
    }
    
    // Symbolic Link Check
    if ([self symbolicLinkCheck] != NOTJAIL) {
        // Jailbroken
        motzart += 2;
    }
    
    // FilesExist Integrity Check
    if ([self filesExistCheck] != NOTJAIL) {
        // Jailbroken
        motzart += 2;
    }
    
    // Check if the Jailbreak Integer is 3 or more
    if (motzart >= 3) {
        // Jailbroken
        return KFJailbroken;
    }
    
    // Not Jailbroken
    return NOTJAIL;
}

#pragma mark - Static Jailbreak Checks

// UIApplication CanOpenURL Check
+ (int)urlCheck {
    @try {
        #if !(defined(__has_feature) && __has_feature(attribute_availability_app_extension))
            // Create a fake url for cydia
            NSURL *fakeURL = [NSURL URLWithString:CYDIAPACKAGE];
            // Return whether or not cydia's openurl item exists
            if ([[UIApplication sharedApplication] canOpenURL:fakeURL])
               return KFOpenURL;
        #endif
    }
    @catch (NSException *exception) {
        // Error, return false
        return NOTJAIL;
    }
    return NOTJAIL;
}

// Cydia Check
+ (int)cydiaCheck {
    @try {
        // Create a file path string
        NSString *filePath = CYDIALOC;
        // Check if it exists
        if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
            // It exists
            return KFCydia;
        } else {
            // It doesn't exist
            return NOTJAIL;
        }
    }
    @catch (NSException *exception) {
        // Error, return false
        return NOTJAIL;
    }
}

// Inaccessible Files Check
+ (int)inaccessibleFilesCheck {
    @try {
        // Run through the array of files
        for (NSString *key in HIDDENFILES) {
            // Check if any of the files exist (should return no)
            if ([[NSFileManager defaultManager] fileExistsAtPath:key]) {
                // Jailbroken
                return KFIFC;
            }
        }
        
        // No inaccessible files found, return NOT Jailbroken
        return NOTJAIL;
    }
    @catch (NSException *exception) {
        // Error, return NOT Jailbroken
        return NOTJAIL;
    }
}

// Plist Check
+ (int)plistCheck {
    @try {
        // Define the Executable name
        NSString *exeName = EXEPATH;
        NSDictionary *ipl = PLISTPATH;
        // Check if the plist exists
        if ([FILECHECK exeName] == FALSE || ipl == nil || ipl.count <= 0) {
            // Executable file can't be found and the plist can't be found...hmmm
            return KFPlist;
        } else {
            // Everything is good
            return NOTJAIL;
        }
    }
    @catch (NSException *exception) {
        // Error, return false
        return NOTJAIL;
    }
}

// Symbolic Link available
+ (int)symbolicLinkCheck {
    @try {
        // See if the Applications folder is a symbolic link
        struct stat s;
        if (lstat("/Applications", &s) != 0) {
            if (s.st_mode & S_IFLNK) {
                // Device is jailbroken
                return KFSymbolic;
            } else
                // Not jailbroken
                return NOTJAIL;
        } else {
            // Not jailbroken
            return NOTJAIL;
        }
    }
    @catch (NSException *exception) {
        // Not Jailbroken
        return NOTJAIL;
    }
}

// FileSystem working correctly?
+ (int)filesExistCheck {
    @try {
        // Check if filemanager is working
        if (![FILECHECK [[NSBundle mainBundle] executablePath]]) {
            // Jailbroken and trying to hide it
            return KFFileExists;
        } else
            // Not Jailbroken
            return NOTJAIL;
    }
    @catch (NSException *exception) {
        // Not Jailbroken
        return NOTJAIL;
    }
}

// Get the running processes
+ (NSArray *)runningProcesses {
    // Define the int array of the kernel's processes
    int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
    size_t miblen = 4;
    
    // Make a new size and int of the sysctl calls
    size_t size = 0;
    int st;
    
    // Make new structs for the processes
    struct kinfo_proc * process = NULL;
    struct kinfo_proc * newprocess = NULL;
    
    // Do get all the processes while there are no errors
    do {
        // Add to the size
        size += (size / 10);
        // Get the new process
        newprocess = realloc(process, size);
        // If the process selected doesn't exist
        if (!newprocess){
            // But the process exists
            if (process){
                // Free the process
                free(process);
            }
            // Return that nothing happened
            return nil;
        }
        
        // Make the process equal
        process = newprocess;
        
        // Set the st to the next process
        st = sysctl(mib, (int)miblen, process, &size, NULL, 0);
        
    } while (st == -1 && errno == ENOMEM);
    
    // As long as the process list is empty
    if (st == 0){
        
        // And the size of the processes is 0
        if (size % sizeof(struct kinfo_proc) == 0){
            // Define the new process
            int nprocess = (int)(size / sizeof(struct kinfo_proc));
            // If the process exists
            if (nprocess){
                // Create a new array
                NSMutableArray * array = [[NSMutableArray alloc] init];
                // Run through a for loop of the processes
                for (int i = nprocess - 1; i >= 0; i--){
                    // Get the process ID
                    NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
                    // Get the process Name
                    NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
                    // Get the process Priority
                    NSString *processPriority = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_priority];
                    // Get the process running time
                    NSDate   *processStartDate = [NSDate dateWithTimeIntervalSince1970:process[i].kp_proc.p_un.__p_starttime.tv_sec];
                    // Create a new dictionary containing all the process ID's and Name's
                    NSDictionary *dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processPriority, processName, processStartDate, nil]
                                                                       forKeys:[NSArray arrayWithObjects:@"ProcessID", @"ProcessPriority", @"ProcessName", @"ProcessStartDate", nil]];
                    
                    // Add the dictionary to the array
                    [array addObject:dict];
                }
                // Free the process array
                free(process);
                
                // Return the process array
                return array;
                
            }
        }
    }
    
    // Free the process array
    free(process);
    
    // If no processes are found, return nothing
    return nil;
}

SSProcessorInfo

获取系统进程信息


// Number of processors
+ (NSInteger)numberProcessors {
    // See if the process info responds to selector
    if ([[NSProcessInfo processInfo] respondsToSelector:@selector(processorCount)]) {
        // Get the number of processors
        NSInteger processorCount = [[NSProcessInfo processInfo] processorCount];
        // Return the number of processors
        return processorCount;
    } else {
        // Return -1 (not found)
        return -1;
    }
}

获取进程数量

// Number of Active Processors
+ (NSInteger)numberActiveProcessors {
    // See if the process info responds to selector
    if ([[NSProcessInfo processInfo] respondsToSelector:@selector(activeProcessorCount)]) {
        // Get the number of active processors
        NSInteger activeprocessorCount = [[NSProcessInfo processInfo] activeProcessorCount];
        // Return the number of active processors
        return activeprocessorCount;
    } else {
        // Return -1 (not found)
        return -1;
    }
}

获取激活的进程数

// Get Processor Usage Information (i.e. ["0.2216801", "0.1009614"])
+ (NSArray *)processorsUsage {
    
    // Try to get Processor Usage Info
    @try {
        // Variables
        processor_info_array_t _cpuInfo, _prevCPUInfo = nil;
        mach_msg_type_number_t _numCPUInfo, _numPrevCPUInfo = 0;
        unsigned _numCPUs;
        NSLock *_cpuUsageLock;
        
        // Get the number of processors from sysctl
        int _mib[2U] = { CTL_HW, HW_NCPU };
        size_t _sizeOfNumCPUs = sizeof(_numCPUs);
        int _status = sysctl(_mib, 2U, &_numCPUs, &_sizeOfNumCPUs, NULL, 0U);
        if (_status)
            _numCPUs = 1;
        
        // Allocate the lock
        _cpuUsageLock = [[NSLock alloc] init];
        
        // Get the processor info
        natural_t _numCPUsU = 0U;
        kern_return_t err = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &_numCPUsU, &_cpuInfo, &_numCPUInfo);
        if (err == KERN_SUCCESS) {
            [_cpuUsageLock lock];
            
            // Go through info for each processor
            NSMutableArray *processorInfo = [NSMutableArray new];
            for (unsigned i = 0U; i < _numCPUs; ++i) {
                Float32 _inUse, _total;
                if (_prevCPUInfo) {
                    _inUse = (
                              (_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER]   - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER])
                              + (_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM])
                              + (_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE]   - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE])
                              );
                    _total = _inUse + (_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE] - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE]);
                } else {
                    _inUse = _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] + _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] + _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE];
                    _total = _inUse + _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE];
                }
                // Add to the processor usage info
                [processorInfo addObject:@(_inUse / _total)];
            }
            
            [_cpuUsageLock unlock];
            if (_prevCPUInfo) {
                size_t prevCpuInfoSize = sizeof(integer_t) * _numPrevCPUInfo;
                vm_deallocate(mach_task_self(), (vm_address_t)_prevCPUInfo, prevCpuInfoSize);
            }
            // Retrieved processor information
            return processorInfo;
        } else {
            // Unable to get processor information
            return nil;
        }
    } @catch (NSException *exception) {
        // Getting processor information failed
        return nil;
    }
}

获取进程的使用情况

SSAccessoryInfo

获取外设信息


// Are any accessories attached?
+ (BOOL)accessoriesAttached {
    // Check if any accessories are connected
    @try {
        // Set up the accessory manger
        EAAccessoryManager *accessoryManager = [EAAccessoryManager sharedAccessoryManager];
        // Get the number of accessories connected
        int numberOfAccessoriesConnected = (int)[accessoryManager.connectedAccessories count];
        // Check if there are any connected
        if (numberOfAccessoriesConnected > 0) {
            // There are accessories connected
            return true;
        } else {
            // There are no accessories connected
            return false;
        }
    }
    @catch (NSException *exception) {
        // Error, return false
        return false;
    }
}

获取外设数量。可参考这篇文章

// Are headphone attached?
+ (BOOL)headphonesAttached {
    // Check if the headphones are connected
    @try {
        // Get the audiosession route information
        AVAudioSessionRouteDescription *route = [[AVAudioSession sharedInstance] currentRoute];
        
        // Run through all the route outputs
        for (AVAudioSessionPortDescription *desc in [route outputs]) {
            
            // Check if any of the ports are equal to the string headphones
            if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones]) {
                
                // Return YES
                return YES;
            }
        }
        
        // No headphones attached
        return NO;
    }
    @catch (NSException *exception) {
        // Error, return false
        return false;
    }
}

是否开启耳机模式


// Number of attached accessories
+ (NSInteger)numberAttachedAccessories {
    // Get the number of attached accessories
    @try {
        // Set up the accessory manger
        EAAccessoryManager *accessoryManager = [EAAccessoryManager sharedAccessoryManager];
        // Get the number of accessories connected
        int numberOfAccessoriesConnected = (int)[accessoryManager.connectedAccessories count];
        // Return how many accessories are attached
        return numberOfAccessoriesConnected;
    }
    @catch (NSException *exception) {
        // Error, return false
        return false;
    }
}

获取连接lighting设备的数量

// Name of attached accessory/accessories (seperated by , comma's)
+ (NSString *)nameAttachedAccessories {
    // Get the name of the attached accessories
    @try {
        // Set up the accessory manger
        EAAccessoryManager *accessoryManager = [EAAccessoryManager sharedAccessoryManager];
        // Set up an accessory (for later use)
        EAAccessory *accessory;
        // Get the number of accessories connected
        int numberOfAccessoriesConnected = (int)[accessoryManager.connectedAccessories count];
        
        // Check to make sure there are accessories connected
        if (numberOfAccessoriesConnected > 0) {
            // Set up a string for all the accessory names
            NSString *allAccessoryNames = @"";
            // Set up a string for the accessory names
            NSString *accessoryName;
            // Get the accessories
            NSArray *accessoryArray = accessoryManager.connectedAccessories;
            // Run through all the accessories
            for (int x = 0; x < numberOfAccessoriesConnected; x++) {
                // Get the accessory at that index
                accessory = [accessoryArray objectAtIndex:x];
                // Get the name of it
                accessoryName = [accessory name];
                // Make sure there is a name
                if (accessoryName == nil || accessoryName.length == 0) {
                    // If there isn't, try and get the manufacturer name
                    accessoryName = [accessory manufacturer];
                }
                // Make sure there is a manufacturer name
                if (accessoryName == nil || accessoryName.length == 0) {
                    // If there isn't a manufacturer name still
                    accessoryName = @"Unknown";
                }
                // Format that name
                allAccessoryNames = [allAccessoryNames stringByAppendingFormat:@"%@", accessoryName];
                if (x < numberOfAccessoriesConnected - 1) {
                    allAccessoryNames = [allAccessoryNames stringByAppendingFormat:@", "];
                }
            }
            // Return the name/s of the connected accessories
            return allAccessoryNames;
        } else {
            // No accessories connected
            return nil;
        }
    }
    @catch (NSException *exception) {
        // Error, return false
        return nil;
    }
}

获取连接lighting设备的名字

相关文章

网友评论

      本文标题:SystemServices 库源码分析(获取设备信息)(2)

      本文链接:https://www.haomeiwen.com/subject/tjfwgftx.html