我想检查设备的iOS版本是否大于3.1.3 我尝试了以下方法:
[[UIDevice currentDevice].systemVersion floatValue]
但是不管用,我只想要一个:
if (version > 3.1.3) { }
我怎样才能做到这一点呢?
我想检查设备的iOS版本是否大于3.1.3 我尝试了以下方法:
[[UIDevice currentDevice].systemVersion floatValue]
但是不管用,我只想要一个:
if (version > 3.1.3) { }
我怎样才能做到这一点呢?
当前回答
使用swift Forget [[UIDevice currentDevice] systemVersion]和NSFoundationVersionNumber检查系统版本的新方法。
我们可以使用NSProcessInfo -isOperatingSystemAtLeastVersion
import Foundation
let yosemite = NSOperatingSystemVersion(majorVersion: 10, minorVersion: 10, patchVersion: 0)
NSProcessInfo().isOperatingSystemAtLeastVersion(yosemite) // false
其他回答
Try:
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
}
使用swift Forget [[UIDevice currentDevice] systemVersion]和NSFoundationVersionNumber检查系统版本的新方法。
我们可以使用NSProcessInfo -isOperatingSystemAtLeastVersion
import Foundation
let yosemite = NSOperatingSystemVersion(majorVersion: 10, minorVersion: 10, patchVersion: 0)
NSProcessInfo().isOperatingSystemAtLeastVersion(yosemite) // false
在Swift中查看iOS版本的解决方案
switch (UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch)) {
case .OrderedAscending:
println("iOS < 8.0")
case .OrderedSame, .OrderedDescending:
println("iOS >= 8.0")
}
这个解决方案的缺点:不管你用哪种方式检查OS版本号,这都是一种糟糕的做法。永远不要以这种方式硬编码依赖关系,总是检查特性、功能或类的存在。考虑这一切;苹果可能会发布一个类的向后兼容版本,如果他们这样做了,那么你建议的代码将永远不会使用它,因为你的逻辑是寻找操作系统版本号,而不是类的存在。
(信息来源)
在Swift中检查类存在的解决方案
if (objc_getClass("UIAlertController") == nil) {
// iOS 7
} else {
// iOS 8+
}
不要使用if (NSClassFromString("UIAlertController") == nil),因为它在使用iOS 7.1和8.2的iOS模拟器上正常工作,但如果你在使用iOS 7.1的真实设备上测试,你会不幸地注意到你永远不会通过代码片段的else部分。
试试这个
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
// do some work
}
作为yasimturks解决方案的一种变体,我定义了一个函数和一些枚举值,而不是五个宏。我觉得它更优雅,但那是个人品味的问题。
用法:
if (systemVersion(LessThan, @"5.0")) ...
. h文件:
typedef enum {
LessThan,
LessOrEqual,
Equal,
GreaterOrEqual,
GreaterThan,
NotEqual
} Comparison;
BOOL systemVersion(Comparison test, NSString* version);
m文件:
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;
}
}
你应该在名称中添加应用程序的前缀,尤其是比较类型。