我想检查设备的 iOS
版本是否大于 3.1.3
我尝试了以下操作:
[[UIDevice currentDevice].systemVersion floatValue]
但它不起作用,我只想要一个:
if (version > 3.1.3) { }
我怎样才能做到这一点?
if #available(iOS 9, *) {}
。在 Objective-c 中启动 Xcode 9,if (@available(iOS 11, *)) {}
。
/*
* 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")) {
...
}
快速回答……
从 Swift 2.0 开始,您可以在 if
或 guard
中使用 #available
来保护只应在某些系统上运行的代码。
if #available(iOS 9, *) {}
在 Objective-C 中,您需要检查系统版本并进行比较。
[[NSProcessInfo processInfo] operatingSystemVersion]
在 iOS 8 及更高版本中。
从 Xcode 9 开始:
if (@available(iOS 9, *)) {}
完整的答案……
在 Objective-C 和极少数情况下的 Swift 中,最好避免依赖操作系统版本作为设备或操作系统功能的指示。通常有一种更可靠的方法来检查特定功能或类是否可用。
检查 API 是否存在:
例如,您可以使用 NSClassFromString
检查 UIPopoverController
在当前设备上是否可用:
if (NSClassFromString(@"UIPopoverController")) {
// Do something
}
对于弱链接类,直接向类发送消息是安全的。值得注意的是,这适用于未明确链接为“必需”的框架。对于缺少的类,表达式的计算结果为 nil,条件不成立:
if ([LAContext class]) {
// Do something
}
某些类(如 CLLocationManager
和 UIDevice
)提供检查设备功能的方法:
if ([CLLocationManager headingAvailable]) {
// Do something
}
检查符号是否存在:
偶尔,您必须检查是否存在常数。这出现在 iOS 8 中,引入了 UIApplicationOpenSettingsURLString
,用于通过 -openURL:
加载设置应用程序。该值在 iOS 8 之前不存在。将 nil 传递给此 API 会崩溃,因此您必须首先注意验证常量的存在:
if (&UIApplicationOpenSettingsURLString != NULL) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
与操作系统版本比较:
假设您面临检查操作系统版本的相对罕见的需求。对于面向 iOS 8 及更高版本的项目,NSProcessInfo
包括一种执行版本比较的方法,出错的可能性较小:
- (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version
针对旧系统的项目可以在 UIDevice
上使用 systemVersion
。 Apple 在其 GLSprite 示例代码中使用它。
// 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
是您想要的,请确保将其视为字符串,否则您可能会截断补丁修订号(例如 3.1.2 -> 3.1)。
UISplitViewController
中发送 -viewWillAppear
。我的技巧是确定是否 < iOS 4.0,并将其发送到根视图的 -didSelectRowAtIndexPath
中的详细视图控制器。
[@"10.0" compare:@"10" options:NSNumericSearch]
返回 NSOrderedDescending
,这很可能根本不是故意的。 (我可能期望 NSOrderedSame
。)这至少是理论上的可能性。
respondsToSelector
等人不会做这项工作 - 必须比较版本。
NSFoundationVersionNumber
,并且只有在不可能的情况下才应该检查 UIDevice
上的系统版本。
正如 official Apple docs 所建议的:您可以使用 NSObjCRuntime.h
头文件中的 NSFoundationVersionNumber
。
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
// here you go with iOS 7
}
NSFoundationVersionNumber_iOS_6_1
在 iOS 5 SDK 中不存在。
#ifndef NSFoundationVersionNumber_iOS_7_0 #define NSFoundationVersionNumber_iOS_7_0 1047.00 #endif
定义它。为了避免这样的混乱,我使用了 yasirmturk 的 SYSTEM_VERSION_LESS_THAN(v) 宏
NSFoundationVersionNumber_iOS_8_0
。只需检查 NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1
在 Objective-C 中启动 Xcode 9:
if (@available(iOS 11, *)) {
// iOS 11 (or newer) ObjC code
} else {
// iOS 10 or older code
}
在 Swift 中启动 Xcode 7:
if #available(iOS 11, *) {
// iOS 11 (or newer) Swift code
} else {
// iOS 10 or older code
}
对于版本,您可以指定 MAJOR、MINOR 或 PATCH(有关定义,请参见 http://semver.org/)。例子:
iOS 11 和 iOS 11.0 是相同的最低版本
iOS 10、iOS 10.3、iOS 10.3.1 是不同的最小版本
您可以为任何这些系统输入值:
iOS、macOS、watchOS、tvOS
取自 one of my pods 的真实案例:
if #available(iOS 10.0, tvOS 10.0, *) {
// iOS 10+ and tvOS 10+ Swift code
} else {
// iOS 9 and tvOS 9 older code
}
if (...) {} else { ... }
guard
而不是在 else
语句中打开块并缩进吗?
if
块,后跟一个 else
。
if
块。
尝试:
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 2.0 中,Apple 使用更方便的语法添加了可用性检查(阅读更多 here)。现在您可以使用更简洁的语法检查操作系统版本:
if #available(iOS 9, *) {
// Then we are on iOS 9
} else {
// iOS 8 or earlier
}
这优于检查 respondsToSelector
等 (What's New In Swift)。现在,如果您没有正确保护代码,编译器将始终警告您。
斯威夫特 2.0 之前
iOS 8 中的新功能是NSProcessInfo
,可以进行更好的语义版本检查。
在 iOS 8 及更高版本上部署
对于 iOS 8.0 或更高版本的最低部署目标,请使用 NSProcessInfo operatingSystemVersion 或 isOperatingSystemAtLeastVersion。
这将产生以下结果:
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 上部署
对于 iOS 7.1 或更低版本的最低部署目标,请在 UIDevice systemVersion 上使用 NSStringCompareOptions.NumericSearch 进行比较。
这将产生:
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 阅读更多内容。
我总是将它们保存在我的 Constants.h 文件中:
#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)
.pch
文件中
pch
文件中导入的 Constants.h
文件中。
+(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-version 项目(Apache 许可证,版本 2.0)中包含的 Version 类,可以轻松获取和比较 iOS 版本。下面的示例代码转储 iOS 版本并检查版本是否大于或等于 6.0。
// 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-version
TakahikoKawasaki/nv-ios-version
博客:在运行时获取 iOS 版本并将其与 Version 类进行比较
Get and compare iOS version at runtime with Version class
我知道这是一个老问题,但应该有人在 Availability.h
中提到了编译时宏。这里的所有其他方法都是运行时解决方案,并且不适用于头文件、类类别或 ivar 定义。
对于这些情况,使用
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0 && defined(__IPHONE_14_0)
// iOS 14+ code here
#else
// Pre iOS 14 code here
#endif
h/t this 答案
一般来说,最好询问一个对象是否可以执行给定的选择器,而不是检查版本号来决定它是否必须存在。
当这不是一个选项时,您确实需要在这里小心一点,因为 [@"5.0" compare:@"5" options:NSNumericSearch]
返回的 NSOrderedDescending
可能根本不是有意的;我可能会在这里期待 NSOrderedSame
。这至少是一个理论上的问题,在我看来,这是一个值得捍卫的问题。
同样值得考虑的是无法合理比较的错误版本输入的可能性。 Apple 提供了三个预定义常量 NSOrderedAscending
、NSOrderedSame
和 NSOrderedDescending
,但如果我无法比较两个事物并且我想返回一个表明这一点的值,我可以想到一个名为 NSOrderedUnordered
的东西的用途.
更重要的是,Apple 有朝一日会扩展他们的三个预定义常量以允许各种返回值,这使得比较 != NSOrderedAscending
不明智,这并非不可能。
话虽如此,请考虑以下代码。
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
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
// Your code here
}
当然,必须将 NSFoundationVersionNumber_iOS_6_1
更改为适用于您要检查的 iOS 版本。在测试设备是否运行 iOS7 或以前的版本时,我现在写的内容可能会被大量使用。
使用 swift Forget [[UIDevice currentDevice] systemVersion] 和 NSFoundationVersionNumber 检查系统版本的新方法。
我们可以使用 NSProcessInfo -isOperatingSystemAtLeastVersion
import Foundation
let yosemite = NSOperatingSystemVersion(majorVersion: 10, minorVersion: 10, patchVersion: 0)
NSProcessInfo().isOperatingSystemAtLeastVersion(yosemite) // false
派对有点晚了,但鉴于 iOS 8.0 的存在,这可能是相关的:
如果你可以避免使用
[[UIDevice currentDevice] systemVersion]
而是检查是否存在方法/类/其他任何东西。
if ([self.yourClassInstance respondsToSelector:@selector(<yourMethod>)])
{
//do stuff
}
我发现它对位置管理器很有用,我必须为 iOS 8.0 调用 requestWhenInUseAuthorization 但该方法不适用于 iOS < 8
UIDevice+IOSVersion.h
@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
#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
#define _kisiOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
if (_kisiOS7) {
NSLog(@"iOS7 or greater")
}
else {
NSLog(@"Less than iOS7");
}
仅用于检索操作系统版本字符串值:
[[UIDevice currentDevice] systemVersion]
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
然后添加一个 if 条件,如下所示:-
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
//Your code
}
有 7.0 或 6.0.3 之类的版本,所以我们可以简单地将版本转换为数字进行比较。如果版本类似于 7.0,只需在其上附加另一个“.0”,然后获取其数值。
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];
对于 6.0.0
if (version==600) {
// Do something
}
7.0
if (version==700) {
// Do something
}
6.1.10
。那么这个算法将产生 6110 > 700
,这是不正确的。
试试下面的代码:
NSString *versionString = [[UIDevice currentDevice] systemVersion];
作为 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;
}
}
您应该将应用程序的前缀添加到名称中,尤其是 Comparison
类型。
使用推荐的推荐方式...如果头文件中没有定义,您始终可以使用所需 IOS 版本的设备在控制台上打印版本。
- (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 版本的解决方案
switch (UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch)) {
case .OrderedAscending:
println("iOS < 8.0")
case .OrderedSame, .OrderedDescending:
println("iOS >= 8.0")
}
此解决方案的缺点:无论您采用哪种方式,检查操作系统版本号都是一种不好的做法。永远不要以这种方式对依赖项进行硬编码,始终检查特性、功能或类的存在。考虑一下; Apple 可能会发布类的向后兼容版本,如果他们这样做了,那么您建议的代码将永远不会使用它,因为您的逻辑会查找操作系统版本号而不是类的存在。
在 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 部分。
#define IsIOS8 (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
Obj-C++ 11 中更通用的版本(您可能可以用 NSString/C 函数替换其中的一些内容,但这不那么冗长。这为您提供了两种机制。splitSystemVersion 为您提供所有部分的数组,如果您只想打开主要版本(例如 switch([self splitSystemVersion][0]) {case 4: break; case 5: break; }
)。
#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;
}
尝试这个
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
// do some work
}
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
float versionToBeCompared = 3.1.3;
甚至无法编译。
实际有效的 Swift 示例:
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 年之前几乎没用
这是一个快速版本:
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)
}
用法:
if iOSVersion.iOS8 {
//Do iOS8 code here
}
struct iOSVersion { static let SYS_VERSION_FLOAT = (UIDevice.currentDevice().systemVersion as NSString).floatValue static let iOS7 = (iOSVersion.SYS_VERSION_FLOAT < 8.0 && iOSVersion.SYS_VERSION_FLOAT >= 7.0) static let iOS8 = (iOSVersion.SYS_VERSION_FLOAT >= 8.0 && iOSVersion.SYS_VERSION_FLOAT < 9.0) static let iOS9 = (iOSVersion.SYS_VERSION_FLOAT >= 9.0 && iOSVersion.SYS_VERSION_FLOAT < 10.0) }
这是 yasirmturk 宏的 Swift 版本。希望它可以帮助一些人
// 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")
.0
数字时应该非常小心。例如SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0.0")
在 iOS 7.0 上给出了不正确的结果。