关于C#:如何查看iOS版本?

How to check iOS version?

我想检查设备的iOS版本是否大于3.1.3。我尝试过这样的事情:

1
[[UIDevice currentDevice].systemVersion floatValue]

但它不起作用,我只想要一个:

1
if (version > 3.1.3) { }

我怎样才能做到这一点?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 *  System Versioning Preprocessor Macros
 */


#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

/*
 *  Usage
 */


if (SYSTEM_VERSION_LESS_THAN(@"4.0")) {
    ...
}

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"3.1.1")) {
    ...
}


*快速的答案……


As of雨燕2.0,你可以在使用前#availableifguardthat should be only保护代码运行在一定的系统。P></

if #available(iOS 9, *) {}

在Objective-C中,You need to check the version和比较系统的性能。P></

在含8和[[NSProcessInfo processInfo] operatingSystemVersion]above。P></

9:Xcode as ofP></

if (@available(iOS 9, *)) {}P></


P></the full的答案……

在Objective-C中,斯威夫特和罕见的案例中,这是最好的操作系统avoid relying on the version of device or as an indication OS的能力。there is usually method of whether更可靠的检查是在前级特征is available。P></

检查:这个API for the ofP></

for example,You can check if UIPopoverControlleris available on the device using NSClassFromString流:P></

1
2
3
if (NSClassFromString(@"UIPopoverController")) {
    // Do something
}

for弱联类,它is to the message directly安全舱。本厂notably for that,as是explicitly联T间的"要求"。for the expression中失踪,evaluates to the condition:零,失败P></

1
2
3
if ([LAContext class]) {
    // Do something
}

一些类,类和方法CLLocationManagerUIDevicedevice to check,提供能力:P></

1
2
3
if ([CLLocationManager headingAvailable]) {
    // Do something
}

检查存在的符号:for the ofP></

你必须非常occasionally check for the,of a常数存在。这肉还必须追踪8 UIApplicationOpenSettingsURLStringwith the used to Load Settings),-openURL:程序路径。the value 8之前还不存在。这将通过无碰撞的API,你必须把爱to verify the first of the constant:生存P></

1
2
3
if (&UIApplicationOpenSettingsURLString != NULL) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}

对操作系统的版本:the?比较P></

让我们假设你面临的relatively with the need to check the珍稀版本操作系统。针对上述项目还为8和表演,包括在NSProcessInfomethod for version with less of error:比较机会P></

1
- (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version

项目的目标系统可以使用UIDevice老年systemVersion在线。苹果在他们的uses EN glsprite样品队列。P></

1
2
3
4
5
6
7
// A system version of 3.1 or greater is required to use CADisplayLink. The NSTimer
// class is used as fallback when it isn't available.
NSString *reqSysVer = @"3.1";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending) {
    displayLinkSupported = TRUE;
}

如果你决定systemVersion无论reason for that is sure to make是你想要的,你把它作为字符串或安补丁修改风险truncating the number(EG。3.1.2→3.1)。P></


正如苹果官方文件所建议的:您可以使用NSFoundationVersionNumber,来自NSObjCRuntime.h头文件。

1
2
3
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    // here you go with iOS 7
}


启动xcode 9,在objective-c中:

1
2
3
4
5
if (@available(iOS 11, *)) {
    // iOS 11 (or newer) ObjC code
} else {
    // iOS 10 or older code
}

启动xcode 7,在swift中:

1
2
3
4
5
if #available(iOS 11, *) {
    // iOS 11 (or newer) Swift code
} else {
    // iOS 10 or older code
}

对于版本,您可以指定major、minor或patch(有关定义,请参阅http://semver.org/)。实例:

  • iOS 11iOS 11.0是相同的最小版本
  • iOS 10iOS 10.3iOS 10.3.1是不同的最小版本。

您可以为这些系统中的任何一个输入值:

  • 江户十一〔15〕、江户十一〔16〕、江户十一〔17〕、江户十一〔18〕。

从我的一个pods中获得的真实案例:

1
2
3
4
5
if #available(iOS 10.0, tvOS 10.0, *) {
    // iOS 10+ and tvOS 10+ Swift code
} else {
    // iOS 9 and tvOS 9 older code
}

文档


这用于检查xcode中的兼容sdk版本,如果您有一个拥有不同版本xcode的大型团队或支持共享相同代码的不同sdk的多个项目:

1
2
3
4
5
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
  //programming in iOS 8+ SDK here
#else
  //programming in lower than iOS 8 here  
#endif

您真正想要的是检查设备上的iOS版本。你可以这样做:

1
2
3
4
5
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
  //older than iOS 8 code here
} else {
  //iOS 8 specific code here
}

SWIFT版:

1
2
3
4
5
if let version = Float(UIDevice.current.systemVersion), version < 9.3 {
    //add lower than 9.3 code here
} else {
    //add 9.3 and above code here
}

当前版本的swift应使用:

1
2
3
4
5
if #available(iOS 12, *) {
    //iOS 12 specific code here
} else {
    //older than iOS 12 code here
}

尝试:P></

1
2
3
4
5
6
NSComparisonResult order = [[UIDevice currentDevice].systemVersion compare: @"3.1.3" options: NSNumericSearch];
if (order == NSOrderedSame || order == NSOrderedDescending) {
    // OS version >= 3.1.3
} else {
    // OS version < 3.1.3
}


首选方法

在Swift2.0中,Apple使用更方便的语法添加了可用性检查(请阅读此处的更多内容)。现在,您可以使用更清晰的语法检查操作系统版本:

1
2
3
4
5
if #available(iOS 9, *) {
    // Then we are on iOS 9
} else {
    // iOS 8 or earlier
}

这比检查respondsToSelector等(swift的新功能)更可取。现在,如果您没有正确地保护代码,编译器将始终警告您。

超速2

iOS8中的新功能是NSProcessInfo,允许更好的语义版本控制检查。

在iOS 8及更高版本上部署

For minimum deployment targets of iOS 8.0 or above, use NSProcessInfo
operatingSystemVersion or isOperatingSystemAtLeastVersion.

这将产生以下结果:

1
2
3
4
5
6
let minimumVersion = NSOperatingSystemVersion(majorVersion: 8, minorVersion: 1, patchVersion: 2)
if NSProcessInfo().isOperatingSystemAtLeastVersion(minimumVersion) {
    //current version is >= (8.1.2)
} else {
    //current version is < (8.1.2)
}

在iOS 7上部署

For minimum deployment targets of iOS 7.1 or below, use compare with
NSStringCompareOptions.NumericSearch on UIDevice systemVersion.

这将产生:

1
2
3
4
5
6
7
8
9
10
11
12
let minimumVersionString ="3.1.3"
let versionComparison = UIDevice.currentDevice().systemVersion.compare(minimumVersionString, options: .NumericSearch)
switch versionComparison {
    case .OrderedSame, .OrderedDescending:
        //current version is >= (3.1.3)
        break
    case .OrderedAscending:
        //current version is < (3.1.3)
        fallthrough
    default:
        break;
}

在NShipster阅读更多。


我总是把它们保存在我的常量.h文件中:

1
2
3
4
5
#define IS_IPHONE5 (([[UIScreen mainScreen] bounds].size.height-568)?NO:YES)
#define IS_OS_5_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0)
#define IS_OS_6_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0)
#define IS_OS_7_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
#define IS_OS_8_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
+(BOOL)doesSystemVersionMeetRequirement:(NSString *)minRequirement{

// eg  NSString *reqSysVer = @"4.0";


  NSString *currSysVer = [[UIDevice currentDevice] systemVersion];

  if ([currSysVer compare:minRequirement options:NSNumericSearch] != NSOrderedAscending)
  {
    return YES;
  }else{
    return NO;
  }


}


使用包含在NV IOS版本项目中的版本类(Apache许可证,版本2.0),很容易获取和比较IOS版本。下面的示例代码将转储iOS版本,并检查该版本是否大于或等于6.0。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Get the system version of iOS at runtime.
NSString *versionString = [[UIDevice currentDevice] systemVersion];

// Convert the version string to a Version instance.
Version *version = [Version versionWithString:versionString];

// Dump the major, minor and micro version numbers.
NSLog(@"version = [%d, %d, %d]",
    version.major, version.minor, version.micro);

// Check whether the version is greater than or equal to 6.0.
if ([version isGreaterThanOrEqualToMajor:6 minor:0])
{
    // The iOS version is greater than or equal to 6.0.
}

// Another way to check whether iOS version is
// greater than or equal to 6.0.
if (6 <= version.major)
{
    // The iOS version is greater than or equal to 6.0.
}

项目页面:nv ios版本
Takahikokawasaki/nv iOS版本

博客:在运行时获取iOS版本并与版本类进行比较
获取并比较运行时的iOS版本和版本类


使用swift forget[uidevice currentdevice]system version]和nsfoundationversionnumber检查系统版本的新方法。

我们可以使用nsprocessinfo-isoperationsystemtaleastversion

1
2
3
4
     import Foundation

     let yosemite = NSOperatingSystemVersion(majorVersion: 10, minorVersion: 10, patchVersion: 0)
     NSProcessInfo().isOperatingSystemAtLeastVersion(yosemite) // false

设备+版本.h

1
2
3
4
5
6
7
8
9
@interface UIDevice (IOSVersion)

+ (BOOL)isCurrentIOSVersionEqualToVersion:(NSString *)iOSVersion;
+ (BOOL)isCurrentIOSVersionGreaterThanVersion:(NSString *)iOSVersion;
+ (BOOL)isCurrentIOSVersionGreaterThanOrEqualToVersion:(NSString *)iOSVersion;
+ (BOOL)isCurrentIOSVersionLessThanVersion:(NSString *)iOSVersion;
+ (BOOL)isCurrentIOSVersionLessThanOrEqualToVersion:(NSString *)iOSVersion

@end

uidevice+iosversion.m版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#import"UIDevice+IOSVersion.h"

@implementation UIDevice (IOSVersion)

+ (BOOL)isCurrentIOSVersionEqualToVersion:(NSString *)iOSVersion
{
    return [[[UIDevice currentDevice] systemVersion] compare:iOSVersion options:NSNumericSearch] == NSOrderedSame;
}

+ (BOOL)isCurrentIOSVersionGreaterThanVersion:(NSString *)iOSVersion
{
    return [[[UIDevice currentDevice] systemVersion] compare:iOSVersion options:NSNumericSearch] == NSOrderedDescending;
}

+ (BOOL)isCurrentIOSVersionGreaterThanOrEqualToVersion:(NSString *)iOSVersion
{
    return [[[UIDevice currentDevice] systemVersion] compare:iOSVersion options:NSNumericSearch] != NSOrderedAscending;
}

+ (BOOL)isCurrentIOSVersionLessThanVersion:(NSString *)iOSVersion
{
    return [[[UIDevice currentDevice] systemVersion] compare:iOSVersion options:NSNumericSearch] == NSOrderedAscending;
}

+ (BOOL)isCurrentIOSVersionLessThanOrEqualToVersion:(NSString *)iOSVersion
{
    return [[[UIDevice currentDevice] systemVersion] compare:iOSVersion options:NSNumericSearch] != NSOrderedDescending;
}

@end

这是在问,如果更好的通用对象选择器窗口可以在西安做了检查,"比在version number to决定if it must be present。P></

When this is not an option,need to be a位你小心这里因为[@"5.0" compare:@"5" options:NSNumericSearch]归来NSOrderedDescendingwhich might not be at all intended阱;NSOrderedSame期望会在这里。This is least在那一个值得关注的理论,是对我国defending。P></

可能性也值得considering is the version of which can not a bad输入reasonably compared to be。该常数的三predefined NSOrderedAscending苹果茶,但我认为NSOrderedSameNSOrderedDescendingfor some of a thing called使用NSOrderedUnorderedin the event)不能出现两个布尔返回值显示在我这。P></

什么是不可能的,黑莓,苹果将扩大他们的三天predefined some of Return to allow在各种常数的值,!= NSOrderedAscendingunwise制作比较。P></

with this说,考虑下面的代码。P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
typedef enum {kSKOrderedNotOrdered = -2, kSKOrderedAscending = -1, kSKOrderedSame = 0, kSKOrderedDescending = 1} SKComparisonResult;

@interface SKComparator : NSObject
+ (SKComparisonResult)comparePointSeparatedVersionNumber:(NSString *)vOne withPointSeparatedVersionNumber:(NSString *)vTwo;
@end

@implementation SKComparator
+ (SKComparisonResult)comparePointSeparatedVersionNumber:(NSString *)vOne withPointSeparatedVersionNumber:(NSString *)vTwo {
  if (!vOne || !vTwo || [vOne length] < 1 || [vTwo length] < 1 || [vOne rangeOfString:@".."].location != NSNotFound ||
    [vTwo rangeOfString:@".."].location != NSNotFound) {
    return SKOrderedNotOrdered;
  }
  NSCharacterSet *numericalCharSet = [NSCharacterSet characterSetWithCharactersInString:@".0123456789"];
  NSString *vOneTrimmed = [vOne stringByTrimmingCharactersInSet:numericalCharSet];
  NSString *vTwoTrimmed = [vTwo stringByTrimmingCharactersInSet:numericalCharSet];
  if ([vOneTrimmed length] > 0 || [vTwoTrimmed length] > 0) {
    return SKOrderedNotOrdered;
  }
  NSArray *vOneArray = [vOne componentsSeparatedByString:@"."];
  NSArray *vTwoArray = [vTwo componentsSeparatedByString:@"."];
  for (NSUInteger i = 0; i < MIN([vOneArray count], [vTwoArray count]); i++) {
    NSInteger vOneInt = [[vOneArray objectAtIndex:i] intValue];
    NSInteger vTwoInt = [[vTwoArray objectAtIndex:i] intValue];
    if (vOneInt > vTwoInt) {
      return kSKOrderedDescending;
    } else if (vOneInt < vTwoInt) {
      return kSKOrderedAscending;
    }
  }
  if ([vOneArray count] > [vTwoArray count]) {
    for (NSUInteger i = [vTwoArray count]; i < [vOneArray count]; i++) {
      if ([[vOneArray objectAtIndex:i] intValue] > 0) {
        return kSKOrderedDescending;
      }
    }
  } else if ([vOneArray count] < [vTwoArray count]) {
    for (NSUInteger i = [vOneArray count]; i < [vTwoArray count]; i++) {
      if ([[vTwoArray objectAtIndex:i] intValue] > 0) {
        return kSKOrderedAscending;
      }
    }
  }
  return kSKOrderedSame;
}
@end

参加派对有点晚,但鉴于iOS 8.0的存在,这可能是相关的:

如果你能避免使用

[[UIDevice currentDevice] systemVersion]

而是检查是否存在方法/类/其他任何方法。

1
2
3
4
if ([self.yourClassInstance respondsToSelector:@selector(<yourMethod>)])
{
    //do stuff
}

我发现它对location manager很有用,当iOS 8.0需要使用授权时,我必须调用requestwhenouseauthorization,但该方法不适用于iOS<8


1
2
3
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
        // Your code here
}

当然,如果要检查的iOS版本适用,则必须将NSFoundationVersionNumber_iOS_6_1更改为。我现在写的东西在测试设备是否运行iOS7或以前的版本时可能会被大量使用。


1
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

然后添加一个if条件,如下所示:

1
2
3
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
   //Your code
}

1
2
3
4
5
6
7
8
#define _kisiOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)

if (_kisiOS7) {
            NSLog(@"iOS7 or greater")
}
else {
           NSLog(@"Less than iOS7");
}


尝试以下代码:

1
NSString *versionString = [[UIDevice currentDevice] systemVersion];

仅用于检索OS版本字符串值:

1
[[UIDevice currentDevice] systemVersion]


有类似7.0或6.0.3的版本,所以我们可以简单地将版本转换为数字进行比较。如果版本与7.0类似,只需在其上附加另一个".0",然后取其数值。

1
2
3
4
5
6
7
8
9
 int version;
 NSString* iosVersion=[[UIDevice currentDevice] systemVersion];
 NSArray* components=[iosVersion componentsSeparatedByString:@"."];
 if ([components count]==2) {
    iosVersion=[NSString stringWithFormat:@"%@.0",iosVersion];

 }
 iosVersion=[iosVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
 version=[iosVersion integerValue];

为0.0.0

1
2
3
  if (version==600) {
    // Do something
  }

为7

1
2
3
 if (version==700) {
   // Do something
 }


使用推荐的方法…如果头文件中没有定义,则可以使用所需iOS versi_n设备在控制台上打印versi_n。

1
2
3
4
5
6
7
8
9
- (BOOL) isIOS8OrAbove{
    float version802 = 1140.109985;
    float version8= 1139.100000; // there is no def like NSFoundationVersionNumber_iOS_7_1 for ios 8 yet?
    NSLog(@"la version actual es [%f]", NSFoundationVersionNumber);
    if (NSFoundationVersionNumber >= version8){
        return true;
    }
    return false;
}

用于在swift中检查iOS版本的解决方案

1
2
3
4
5
6
7
switch (UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch)) {
    case .OrderedAscending:
       println("iOS < 8.0")

    case .OrderedSame, .OrderedDescending:
       println("iOS >= 8.0")
}

这个解决方案的缺点:用操作系统的版本号来检查,不管你用什么方法,都是不好的做法。人们不应该用这种方式硬编码依赖关系,总是检查特性、功能或类的存在。考虑到这一点;苹果可能会发布类的向后兼容版本,如果他们这样做了,那么您建议的代码将永远不会使用它,因为您的逻辑寻找的是操作系统版本号,而不是类的存在。

(此信息的来源)

在swift中检查类存在性的解决方案

1
2
3
4
5
if (objc_getClass("UIAlertController") == nil) {
   // iOS 7
} else {
   // iOS 8+
}

不要使用if (NSClassFromString("UIAlertController") == nil),因为它在使用iOS 7.1和8.2的iOS模拟器上工作正常,但是如果您在使用iOS 7.1的真实设备上进行测试,您会很遗憾地注意到,您永远不会通过代码片段的其他部分。


作为Yasimturks解决方案的变体,我定义了一个函数和一些枚举值,而不是五个宏。我觉得它更优雅,但这是一个品味问题。

用途:

1
if (systemVersion(LessThan, @"5.0")) ...

h文件:

1
2
3
4
5
6
7
8
9
10
typedef enum {
  LessThan,
  LessOrEqual,
  Equal,
  GreaterOrEqual,
  GreaterThan,
  NotEqual
} Comparison;

BOOL systemVersion(Comparison test, NSString* version);

m文件:

1
2
3
4
5
6
7
8
9
10
11
BOOL systemVersion(Comparison test, NSString* version) {
  NSComparisonResult result = [[[UIDevice currentDevice] systemVersion] compare: version options: NSNumericSearch];
  switch (test) {
    case LessThan:       return result == NSOrderedAscending;
    case LessOrEqual:    return result != NSOrderedDescending;
    case Equal:          return result == NSOrderedSame;
    case GreaterOrEqual: return result != NSOrderedAscending;
    case GreaterThan:    return result == NSOrderedDescending;
    case NotEqual:       return result != NSOrderedSame;
  }
}

您应该将应用程序的前缀添加到名称中,尤其是Comparison类型中。


我知道这是个老问题,但应该有人提到Availability.h中的编译时宏。这里的所有其他方法都是运行时解决方案,不能在头文件、类类别或IVAR定义中工作。

对于这些情况,使用

1
2
3
4
5
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
  // iOS 6+ code here
#else
  // Pre iOS 6 code here
#endif

H/T这个答案


1
#define IsIOS8 (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)

在项目中添加下面的Swift代码,轻松访问iOS版本和设备等信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class DeviceInfo: NSObject {

    struct ScreenSize
    {
        static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
        static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
        static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
        static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
    }

    struct DeviceType
    {
        static let IS_IPHONE_4_OR_LESS =  UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
        static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
        static let IS_IPHONE_6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH >= 667.0
        static let IS_IPHONE_6P = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
        static let IS_IPHONE_X = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 812.0
        static let IS_IPAD      = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0
        static let IS_IPAD_PRO  = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0
    }

    struct VersionType{
        static let SYS_VERSION_FLOAT = (UIDevice.current.systemVersion as NSString).floatValue
        static let iOS7 = (VersionType.SYS_VERSION_FLOAT < 8.0 && VersionType.SYS_VERSION_FLOAT >= 7.0)
        static let iOS8 = (VersionType.SYS_VERSION_FLOAT >= 8.0 && VersionType.SYS_VERSION_FLOAT < 9.0)
        static let iOS9 = (VersionType.SYS_VERSION_FLOAT >= 9.0 && VersionType.SYS_VERSION_FLOAT < 10.0)
        static let iOS10 = (VersionType.SYS_VERSION_FLOAT >= 9.0 && VersionType.SYS_VERSION_FLOAT < 11.0)
    }
}

以下是一个快速版本:

1
2
3
4
5
6
struct iOSVersion {
    static let SYS_VERSION_FLOAT = (UIDevice.currentDevice().systemVersion as NSString).floatValue
    static let iOS7 = (Version.SYS_VERSION_FLOAT < 8.0 && Version.SYS_VERSION_FLOAT >= 7.0)
    static let iOS8 = (Version.SYS_VERSION_FLOAT >= 8.0 && Version.SYS_VERSION_FLOAT < 9.0)
    static let iOS9 = (Version.SYS_VERSION_FLOAT >= 9.0 && Version.SYS_VERSION_FLOAT < 10.0)
}

用途:

1
2
3
if iOSVersion.iOS8 {
    //Do iOS8 code here
}


试试这个

1
2
3
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
// do some work
}


桑葚Generic version - 11在C + +对象(你可以是some of this东西probably replace with the nsstring / C函数的this is,but less详细。给你这两个机制。给你splitsystemversion安阵列部分,which is useful?如果你只是想在网络交换机(例如switch([self splitSystemVersion][0]) {case 4: break; case 5: break; }茶叶专业版本)。P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <boost/lexical_cast.hpp>

- (std::vector<int>) splitSystemVersion {
    std::string version = [[[UIDevice currentDevice] systemVersion] UTF8String];
    std::vector<int> versions;
    auto i = version.begin();

    while (i != version.end()) {
        auto nextIllegalChar = std::find_if(i, version.end(), [] (char c) -> bool { return !isdigit(c); } );
        std::string versionPart(i, nextIllegalChar);
        i = std::find_if(nextIllegalChar, version.end(), isdigit);

        versions.push_back(boost::lexical_cast<int>(versionPart));
    }

    return versions;
}

/** Losslessly parse system version into a number
 * @return <0>: the version as a number,
 * @return <1>: how many numeric parts went into the composed number. e.g.
 * X.Y.Z = 3.  You need this to know how to compare again <0>
 */

- (std::tuple<int, int>) parseSystemVersion {
    std::string version = [[[UIDevice currentDevice] systemVersion] UTF8String];
    int versionAsNumber = 0;
    int nParts = 0;

    auto i = version.begin();
    while (i != version.end()) {
        auto nextIllegalChar = std::find_if(i, version.end(), [] (char c) -> bool { return !isdigit(c); } );
        std::string versionPart(i, nextIllegalChar);
        i = std::find_if(nextIllegalChar, version.end(), isdigit);

        int part = (boost::lexical_cast<int>(versionPart));
        versionAsNumber = versionAsNumber * 100 + part;
        nParts ++;
    }

    return {versionAsNumber, nParts};
}


/** Assume that the system version will not go beyond X.Y.Z.W format.
 * @return The version string.
 */

- (int) parseSystemVersionAlt {
    std::string version = [[[UIDevice currentDevice] systemVersion] UTF8String];
    int versionAsNumber = 0;
    int nParts = 0;

    auto i = version.begin();
    while (i != version.end() && nParts < 4) {
        auto nextIllegalChar = std::find_if(i, version.end(), [] (char c) -> bool { return !isdigit(c); } );
        std::string versionPart(i, nextIllegalChar);
        i = std::find_if(nextIllegalChar, version.end(), isdigit);

        int part = (boost::lexical_cast<int>(versionPart));
        versionAsNumber = versionAsNumber * 100 + part;
        nParts ++;
    }

    // don't forget to pad as systemVersion may have less parts (i.e. X.Y).
    for (; nParts < 4; nParts++) {
        versionAsNumber *= 100;
    }

    return versionAsNumber;
}

这是Yasirmturk宏的快速版本。希望它能帮助一些人

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// MARK: System versionning

func SYSTEM_VERSION_EQUAL_TO(v: String) -> Bool {
    return UIDevice.currentDevice().systemVersion.compare(v, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedSame
}

func SYSTEM_VERSION_GREATER_THAN(v: String) -> Bool {
    return UIDevice.currentDevice().systemVersion.compare(v, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedDescending
}

func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v: String) -> Bool {
    return UIDevice.currentDevice().systemVersion.compare(v, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedAscending
}

func SYSTEM_VERSION_LESS_THAN(v: String) -> Bool {
    return UIDevice.currentDevice().systemVersion.compare(v, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending
}

func SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v: String) -> Bool {
    return UIDevice.currentDevice().systemVersion.compare(v, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedDescending
}

let kIsIOS7: Bool = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO("7")
let kIsIOS7_1: Bool = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO("7.1")
let kIsIOS8: Bool = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO("8")
let kIsIOS9: Bool = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO("9")

1
2
3
4
5
6
7
float deviceOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
float versionToBeCompared = 3.1.3; //(For Example in your case)

if(deviceOSVersion < versionToBeCompared)
   //Do whatever you need to do. Device version is lesser than 3.1.3(in your case)
else
   //Device version should be either equal to the version you specified or above


实际有效的Swift示例:

1
2
3
4
5
6
switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) {
case .OrderedSame, .OrderedDescending:
    println("iOS >= 8.0")
case .OrderedAscending:
    println("iOS < 8.0")
}

不要使用nsprocessinfo,因为它在8.0下不工作,所以它在2016年之前几乎是无用的。


这两个流行的答案存在一些问题:

  • 使用NSNumericSearch比较字符串有时会产生非必然的结果(SYSTEM_VERSION_*宏都会受到这种影响):

    1
    [@"10.0" compare:@"10" options:NSNumericSearch] // returns NSOrderedDescending instead of NSOrderedSame

    修复:首先规范化字符串,然后执行比较。尝试以相同的格式获取两个字符串可能会很烦人。

  • 在检查未来版本时不可能使用基础框架版本符号

    1
    NSFoundationVersionNumber_iOS_6_1 // does not exist in iOS 5 SDK

    修复:执行两个单独的测试以确保符号存在,然后比较符号。然而,这里的另一个:

  • 基础框架版本符号不是唯一的iOS版本。多个iOS版本可以具有相同的框架版本。

    1
    2
    9.2 & 9.3 are both 1242.12
    8.3 & 8.4 are both 1144.17

    修正:我认为这个问题是无法解决的。

  • 为了解决这些问题,下面的方法将版本号字符串视为基数10000个数字(每个主要/次要/修补组件都是一个单独的数字),并执行基数转换为十进制,以便使用整数运算符进行比较。

    为了方便地比较iOS版本字符串和比较具有任意数量组件的字符串,还添加了另外两种方法。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    + (SInt64)integerFromVersionString:(NSString *)versionString withComponentCount:(NSUInteger)componentCount
    {
        //
        // performs base conversion from a version string to a decimal value. the version string is interpreted as
        // a base-10000 number, where each component is an individual digit. this makes it simple to use integer
        // operations for comparing versions. for example (with componentCount = 4):
        //
        //   version"5.9.22.1" = 5*1000^3 + 9*1000^2 + 22*1000^1 + 1*1000^0 = 5000900220001
        //    and
        //   version"6.0.0.0" = 6*1000^3 + 0*1000^2 + 0*1000^1 + 0*1000^1 = 6000000000000
        //    and
        //   version"6" = 6*1000^3 + 0*1000^2 + 0*1000^1 + 0*1000^1 = 6000000000000
        //
        // then the integer comparisons hold true as you would expect:
        //
        //  "5.9.22.1" <"6.0.0.0" // true
        //  "6.0.0.0" =="6"       // true
        //

        static NSCharacterSet *nonDecimalDigitCharacter;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken,
            ^{  // don't allocate this charset every time the function is called
                nonDecimalDigitCharacter = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
            });

        SInt64 base    = 10000; // each component in the version string must be less than base
        SInt64 result  =     0;
        SInt64 power   =     0;

        // construct the decimal value left-to-right from the version string
        for (NSString *component in [versionString componentsSeparatedByString:@"."])
        {
            if (NSNotFound != [component rangeOfCharacterFromSet:nonDecimalDigitCharacter].location)
            {
                // one of the version components is not an integer, so bail out
                result = -1;
                break;
            }
            result += [component longLongValue] * (long long)pow((double)base, (double)(componentCount - ++power));
        }

        return result;
    }

    + (SInt64)integerFromVersionString:(NSString *)versionString
    {
        return [[self class] integerFromVersionString:versionString
                                   withComponentCount:[[versionString componentsSeparatedByString:@"."] count]];
    }

    + (SInt64)integerFromiOSVersionString:(NSString *)versionString
    {
        // iOS uses 3-component version string
        return [[self class] integerFromVersionString:versionString
                                   withComponentCount:3];
    }

    它支持许多修订标识符(通过4位数字,0-9999;更改base以调整此范围),并且可以支持任意数量的组件(苹果目前似乎使用3个组件,例如major.minor.patch),但这可以使用componentCount参数明确指定。确保你的componentCountbase不会造成溢出,即确保2^63 >= base^componentCount

    使用实例:

    1
    2
    3
    4
    5
    NSString *currentVersion = [[UIDevice currentDevice] systemVersion];
    if ([Util integerFromiOSVersionString:currentVersion] >= [Util integerFromiOSVersionString:@"42"])
    {
        NSLog(@"we are in some horrible distant future where iOS still exists");
    }

    我的解决方案是添加在实用工具类(HINT method to your version to the HINT)交流系统补偿和manually浮法number for序。P></

    This is also,尾巴相当简单,我希望它newbies helps some。在简单的目标和通行证在浮法bool,回来。P></

    宣布,它在你的共享类的这样:P></

    1
    (+) (BOOL) iOSMeetsOrExceedsVersion:(float)targetVersion;

    呼叫它这样:P></

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    BOOL shouldBranch = [SharedClass iOSMeetsOrExceedsVersion:5.0101];

    (+) (BOOL) iOSMeetsOrExceedsVersion:(float)targetVersion {

    /*
     Note: the incoming targetVersion should use 2 digits for each subVersion --

     example 5.01 for v5.1, 5.11 for v5.11 (aka subversions above 9), 5.0101 for v5.1.1, etc.
    */


    // Logic: as a string, system version may have more than 2 segments (example: 5.1.1)
    // so, a direct conversion to a float may return an invalid number
    // instead, parse each part directly

    NSArray *sysVersion = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
    float floatVersion = [[sysVersion objectAtIndex:0] floatValue];
    if (sysVersion.count > 1) {
        NSString* subVersion = [sysVersion objectAtIndex:1];
        if (subVersion.length == 1)
            floatVersion += ([[sysVersion objectAtIndex:1] floatValue] *0.01);
        else
            floatVersion += ([[sysVersion objectAtIndex:1] floatValue] *0.10);
    }
    if (sysVersion.count > 2) {
        NSString* subVersion = [sysVersion objectAtIndex:2];
        if (subVersion.length == 1)
            floatVersion += ([[sysVersion objectAtIndex:2] floatValue] *0.0001);
        else
            floatVersion += ([[sysVersion objectAtIndex:2] floatValue] *0.0010);
    }

    if (floatVersion  >= targetVersion)
        return TRUE;

    // else
    return FALSE;
     }

    所有答案看起来都有点大。我只是使用:

    1
    2
    3
    4
    5
    if (SYSTEM_VERSION_GREATER_THAN(@"7.0")){(..CODE...)}
    if (SYSTEM_VERSION_EQUAL_TO(@"7.0")){(..CODE...)}
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")){(..CODE...)}
    if (SYSTEM_VERSION_LESS_THAN(@"7.0")){(..CODE...)}
    if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(@"7.0")){(..CODE...)}

    当然,用所需的操作系统版本替换@"7.0"


  • 在主屏幕上,点击设置>常规>关于。
  • 设备的软件版本应显示在此屏幕上。
  • 检查版本号是否大于3.1.3