检查Swift中的操作系统版本?

我试图在Swift中检查系统信息。 我发现,这可以通过代码来实现:

var sysData:CMutablePointer<utsname> = nil let retVal:CInt = uname(sysData) 

我有这个代码的两个问题:

  1. 什么应该是sysData的初始值? 这个例子在retVal中给出-1可能是因为sysData是零。
  2. 我如何从sysData中读取信息?

对于iOS,请尝试:

 var systemVersion = UIDevice.current.systemVersion 

对于OS X,请尝试:

 var systemVersion = NSProcessInfo.processInfo().operatingSystemVersion 

如果您只想检查用户是否至less运行特定版本,则还可以使用以下适用于iOS和OS X的Swift 2function:

 if #available(iOS 9.0, *) { // use the feature only available in iOS 9 // for ex. UIStackView } else { // or use some work around } 

但不build议检查操作系统版本。 比较版本号,最好检查一下你想使用的function是否可用。 对于iOS,如上所述,您应该检查它是否响应select器; 例如。:

 if (self.respondsToSelector(Selector("showViewController"))) { self.showViewController(vc, sender: self) } else { // some work around } 

更新:
现在你应该使用Swift 2引入的新的可用性检查
例如要在编译时检查iOS 9.0或更高版本,请使用以下命令:

 if #available(iOS 9.0, *) { // use UIStackView } else { // show sad face emoji } 

或者可以与整个方法或类一起使用

 @available(iOS 9.0, *) func useStackView() { // use UIStackView } 

欲了解更多信息,请参阅。

运行时间检查:

如果你不想要确切的版本,但要检查iOS 9,10或11使用if:

 let floatVersion = (UIDevice.current.systemVersion as NSString).floatValue 

编辑:刚刚find另一种方式来实现这一点:

 let iOS8 = floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1) let iOS7 = floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_7_1) 

我做了从下面的链接转移到快速帮助函数:

我们如何以编程方式检测哪个iOS版本的设备正在运行?

 func SYSTEM_VERSION_EQUAL_TO(version: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedSame } func SYSTEM_VERSION_GREATER_THAN(version: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedDescending } func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedAscending } func SYSTEM_VERSION_LESS_THAN(version: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending } func SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(version: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedDescending } 

它可以像这样使用:

 SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO("7.0") 

Swift 3.0

我们不需要创build扩展,因为ProcessInfo给我们的版本信息。 你可以看到iOS的示例代码如下。

 let os = ProcessInfo().operatingSystemVersion switch (os.majorVersion, os.minorVersion, os.patchVersion) { case (8, 0, _): print("iOS >= 8.0.0, < 8.1.0") case (8, _, _): print("iOS >= 8.1.0, < 9.0") case (9, _, _): print("iOS >= 9.0.0") default: // this code will have already crashed on iOS 7, so >= iOS 10.0 println("iOS >= 10.0.0") } 

参考: http : //nshipster.com/swift-system-version-checking/

我为了简单的使用这个Singleton, 创build了一个IOSVersion.swift文件并添加了下面的代码:

 import UIKit public class IOSVersion { class func SYSTEM_VERSION_EQUAL_TO(version: NSString) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedSame } class func SYSTEM_VERSION_GREATER_THAN(version: NSString) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version as String, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedDescending } class func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: NSString) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version as String, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedAscending } class func SYSTEM_VERSION_LESS_THAN(version: NSString) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version as String, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending } class func SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(version: NSString) -> Bool { return UIDevice.currentDevice().systemVersion.compare(version as String, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedDescending } } 

使用 :

 IOSVersion.SYSTEM_VERSION_EQUAL_TO("8.0") IOSVersion.SYSTEM_VERSION_LESS_THAN("8.0") 

谢谢@KVISH

编辑Swift 2:

 if #available(iOS 9.0, *) { // 👍 } else { // 👎 } 

如果您使用的是Swift 2,并且想要检查操作系统版本以使用某个API,则可以使用新的可用性function:

 if #available(iOS 8, *) { //iOS 8+ code here. } else { //Code for iOS 7 and older versions. //An important note: if you use #availability, Xcode will also //check that you don't use anything that was introduced in iOS 8+ //inside this `else` block. So, if you try to use UIAlertController //here, for instance, it won't compile. And it's great. } 

我写了这个答案,因为这是在谷歌的第一个问题, swift 2 check system version查询。

更新Swift 3.0+

 func SYSTEM_VERSION_EQUAL_TO(version: String) -> Bool { return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedSame } func SYSTEM_VERSION_GREATER_THAN(version: String) -> Bool { return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedDescending } func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: String) -> Bool { return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedAscending } func SYSTEM_VERSION_LESS_THAN(version: String) -> Bool { return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedAscending } func SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(version: String) -> Bool { return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedDescending } 
 let Device = UIDevice.currentDevice() let iosVersion = NSString(string: Device.systemVersion).doubleValue let iOS8 = iosVersion >= 8 let iOS7 = iosVersion >= 7 && iosVersion < 8 

并检查为

 if(iOS8) { } else { } 

马特汤普森分享一个非常方便的方式

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

Swift 3中检查MacOS和iOS版本

IOS

  extension UIDevice { var iOS: Double? { if UIDevice.current.systemName == "iOS" { if let iosVersion = UIDevice.current.systemVersion.toDouble { return iosVersion } } return nil } } extension String { var toDouble: Double? { if let iosVersion = Double(self) { return iosVersion } var arr = components(separatedBy: ".") if arr.count >= 1 { var integerPart = 0 var floatPart = 0 if let _integerPart = Int(arr[0]), !arr[0].isEmpty{ integerPart = _integerPart } if let _floatPart = Int(arr[1]), !arr[1].isEmpty{ floatPart = _floatPart } return Double("\(integerPart).\(floatPart)") } return nil } } 

版本string转换示例

 var stringVersion = "10.1.1" print(stringVersion.toDouble!) // print 10.1 stringVersion = ".5.35" print(stringVersion.toDouble!) // print 0.5 stringVersion = "..35" print(stringVersion.toDouble!) // print 0.0 

用法

 if let iosVersion = UIDevice.current.iOS { if iosVersion >= 8.0 { print("current version: \(iosVersion)") } } 

苹果系统

 extension ProcessInfo { var OS: Double? { let result = "\(ProcessInfo.processInfo.operatingSystemVersion.majorVersion).\(ProcessInfo.processInfo.operatingSystemVersion.minorVersion)" return Double(result) } } 

用法

 // check os version if let systemVersion = ProcessInfo.processInfo.OS { if systemVersion >= 10.1 { print("current version: \(systemVersion)") } } 

在Swift 2和更高版本中检查系统版本(以及许多其他版本)的最简单和最简单的方法是:

 if #available(iOS 9.0, *) { // check for iOS 9.0 and later } 

此外,使用#available你可以检查这些版本:

 iOS iOSApplicationExtension macOS macOSApplicationExtension watchOS watchOSApplicationExtension tvOS tvOSApplicationExtension swift 

注意:在iOS 8.0和更高版本中可用。 OS X v10.10及更高版本

 var majorVersion: Int { return NSProcessInfo.processInfo().operatingSystemVersion.majorVersion } var minorVersion: Int { return NSProcessInfo.processInfo().operatingSystemVersion.minorVersion } var patchVersion: Int { return NSProcessInfo.processInfo().operatingSystemVersion.patchVersion } var myOSVersion: String { return NSProcessInfo.processInfo().operatingSystemVersionString } 

基于马特汤普森的答案,这里是一个方法与相应的unit testing,在iOS 7和以上 (包括iOS 9 ,不再让你检查NSFoundationNumber )与SwiftObjective-c 一起工作

 + (BOOL) isAtLeastOSVersion:(NSString *)osVersion { switch ([[UIDevice currentDevice].systemVersion compare:osVersion options:NSNumericSearch]) { case NSOrderedSame: case NSOrderedDescending: return YES; default: return NO; } } 

 @interface ANFakeCurrDevice : NSObject @property (nonatomic, strong) NSString *systemVersion; @end @implementation ANFakeCurrDevice @end @implementation MyHelperClassUnitTests - (void)setUp { [super setUp]; } - (void)tearDown { [super tearDown]; } - (void)test_isAtLeastOSVersion { id deviceMock = [OCMockObject niceMockForClass:[UIDevice class]]; ANFakeCurrDevice *fakeCurrDevice = [ANFakeCurrDevice new]; fakeCurrDevice.systemVersion = @"99.9.9"; [[[deviceMock stub] andReturn:fakeCurrDevice] currentDevice]; XCTAssertTrue([[UIDevice currentDevice].systemVersion isEqualToString:@"99.9.9"]); fakeCurrDevice.systemVersion = @"1.0.1"; XCTAssertTrue([ANConstants isAtLeastOSVersion:@"1"]); XCTAssertTrue([ANConstants isAtLeastOSVersion:@"1.0"]); XCTAssertTrue([ANConstants isAtLeastOSVersion:@"1.0.1"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"1.0.2"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"1.1.0"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"2"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"2.0"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"2.0.0"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"2.0.1"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"2.1.0"]); fakeCurrDevice.systemVersion = @"8.4.0"; XCTAssertTrue([ANConstants isAtLeastOSVersion:@"7.0.1"]); XCTAssertTrue([ANConstants isAtLeastOSVersion:@"8"]); XCTAssertTrue([ANConstants isAtLeastOSVersion:@"8.4"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"8.4.1"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"8.4.2"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"9.0"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"9.0.1"]); XCTAssertFalse([ANConstants isAtLeastOSVersion:@"9.0.2"]); XCTAssertTrue([ANConstants isAtLeastOSVersion:@"8.4"] && ![ANConstants isAtLeastOSVersion:@"9.0"]); fakeCurrDevice.systemVersion = @"8.4.1"; XCTAssertTrue([ANConstants isAtLeastOSVersion:@"8.4"] && ![ANConstants isAtLeastOSVersion:@"9.0"]); } @end 

另外如果你想检查WatchOS。

迅速

 let watchOSVersion = WKInterfaceDevice.currentDevice().systemVersion print("WatchOS version: \(watchOSVersion)") 

Objective-C的

 NSString *watchOSVersion = [[WKInterfaceDevice currentDevice] systemVersion]; NSLog(@"WatchOS version: %@", watchOSVersion); 
 let osVersion = NSProcessInfo.processInfo().operatingSystemVersion let versionString = osVersion.majorVersion.description + "." + osVersion.minorVersion.description + "." + osVersion.patchVersion.description print(versionString) 

获取当前版本的系统并将其拆分。 所以你可以得到主要和次要版本。

 let sys_version = UIDevice.current.systemVersion let all_version = sys_version.components(separatedBy: ".") print("Major version : \(all_version[0])") print("Minor version : \(all_version[1])") 

这里编写的大部分示例代码都会得到超出预期的结果。 例如,

 func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: String) -> Bool { return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedAscending } 

在iOS“10.3”中,通过“10.3.0”版本的这个方法不会返回true。 这样的结果是没有意义的,它们必须被视为相同的版本。 为了得到准确的比较结果,我们必须考虑比较版本string中的所有数字组件。 此外,提供所有大写字母的全球方法并不是一个好的方法。 由于我们在SDK中使用的版本types是一个string,因此在String中扩展比较function是有意义的。

要比较系统版本,以下所有示例都应该可以工作。

 XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThan: "99.0.0")) XCTAssertTrue(UIDevice.current.systemVersion.isVersion(equalTo: UIDevice.current.systemVersion)) XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThan: "3.5.99")) XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThanOrEqualTo: "10.3.0.0.0.0.0.0")) XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThanOrEqualTo: "10.3")) 

你可以在我的仓库https://github.com/DragonCherry/VersionCompare查&#x770B;