How to check iPhone Device Version in iOS?

后端 未结 5 1723
长情又很酷
长情又很酷 2021-01-01 04:46

Hi i would like to check iPhone Device Version in iOS.

I mean , currently running device is iPhone 4 or iPhone 5.

I need to check the device , is that iPhone

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 05:21

    Based on the answers of this question you could determined which model your are using by this:

    NSString *deviceModel = [UIDevice currentDevice].model;
    

    Results can be one of the values: iPod touch, iPhone, iPad, iPhone Simulator, iPad Simulator

    For specific model which version you are using could be determined by creating a Category on UIDevice.h class like this:

    UIDevice+Utilities.h

    #import 
    
    @interface UIDevice (Utilities)
    
    - (CGFloat)deviceModelVersion;
    
    @end
    

    UIDevice+Utilities.m

    #import "UIDevice+Utilities.h"
    #include 
    #include 
    
    @implementation UIDevice (Utilities)
    
    - (CGFloat)deviceModelVersion
    {
        size_t size;
        sysctlbyname("hw.machine", NULL, &size, NULL, 0);
        char *machine = malloc(size);
        sysctlbyname("hw.machine", machine, &size, NULL, 0);
        NSString *platform = [NSString stringWithUTF8String:machine];
        free(machine);
    
        if ([platform rangeOfString:@"iPhone"].location != NSNotFound)
        {
            return [[[platform stringByReplacingOccurrencesOfString:@"iPhone" withString:@""] stringByReplacingOccurrencesOfString:@"," withString:@"."] floatValue];
        }
        else if ([platform rangeOfString:@"iPad"].location != NSNotFound)
        {
            return [[[platform stringByReplacingOccurrencesOfString:@"iPad" withString:@""] stringByReplacingOccurrencesOfString:@"," withString:@"."] floatValue];
        }
        else if ([platform rangeOfString:@"iPod"].location != NSNotFound)
        {
            return [[[platform stringByReplacingOccurrencesOfString:@"iPod" withString:@""] stringByReplacingOccurrencesOfString:@"," withString:@"."] floatValue];
        }
        else if ([platform rangeOfString:@"i386"].location != NSNotFound || [platform rangeOfString:@"x86_64"].location != NSNotFound)
        {
            return -1.0; //Currently it is not possible (or maybe it is, but I do not know)
                         //which type of simulator device model version your app is running
                         //so I am returning -1.0 device model version for all simulators types
        }
    
        return 0.0;
    }
    
    @end
    

    Example how to call function deviceModelVersion:

    CGFloat deviceModelVersion = [UIDevice currentDevice].deviceModelVersion;
    

    Possible results could be 1.0, 1.1, ..., 2.0, 2.1, ..., 3.0, 3.1, .., 4.0, 4.1, .., 5.0, 5.1, ...

    To determine if it is iPhone 5, you would have

    deviceModel : "iPhone" 
    

    and

    deviceModelVersion : >=5.0 and < 6.0
    

提交回复
热议问题