ios - bar - swift poptorootviewcontroller




如何檢查iOS版本? (20)

首選方法

在Swift 2.0中,Apple使用更簡便的語法增加了可用性檢查(請閱讀here )。 現在您可以使用更清晰的語法檢查操作系統版本:

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

這是檢查respondsToSelector等首選( Swift中有什麼新功能 )。 現在編譯器會一直警告你,如果你沒有正確地守護你的代碼。

Pre Swift 2.0

iOS 8中的新功能是NSProcessInfo可以進行更好的語義版本檢查。

部署在iOS 8和更高版本上

對於iOS 8.0或更高版本的最低部署目標,請使用NSProcessInfo operatingSystemVersionisOperatingSystemAtLeastVersion

這將產生以下結果:

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

我想檢查設備的iOS版本是否大於3.1.3我嘗試瞭如下方法:

[[UIDevice currentDevice].systemVersion floatValue]

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

if (version > 3.1.3) { }

我怎樣才能做到這一點?


快速回答...


從Swift 2.0開始,您可以在ifguard使用#available來保護只應在特定係統上運行的代碼。

if #available(iOS 9, *) {}


在Objective-C中,您需要檢查系統版本並進行比較。

iOS 8及更高版本中的[[NSProcessInfo processInfo] operatingSystemVersion]

從Xcode 9開始:

if (@available(iOS 9, *)) {}


完整的答案...

在極少數情況下,在Objective-C和Swift中,最好避免依賴操作系統版本作為設備或操作系統功能的指示。 通常有一種更可靠的方法來檢查特定功能或類是否可用。

檢查是否存在API:

例如,您可以使用NSClassFromString檢查當前設備上的UIPopoverController是否可用:

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

對於弱連接的類,直接向類發送消息是安全的。 值得注意的是,這適用於沒有明確鏈接為“必需”的框架。 對於缺失的類,表達式評估為零,失敗條件:

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

某些類,如CLLocationManagerUIDevice ,提供了檢查設備功能的方法:

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

針對舊系統的項目可以使用systemVersion上的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)。


在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")
}

Con解決方案:根據操作系統版本號進行檢查是一種不好的做法,無論採用哪種方式。 One should never hard code dependencies in this way, always check for features, capabilities or the existence of a class. Consider this; Apple may release a backwards compatible version of a class, if they did then the code you suggest would never use it as your logic looks for an OS version number and NOT the existence of the class.

( NSHipster )

Solution for checking the class existence in Swift

if (objc_getClass("UIAlertController") == nil) {
   // iOS 7
} else {
   // iOS 8+
}

Do not use if (NSClassFromString("UIAlertController") == nil) because it works correctly on the iOS simulator using iOS 7.1 and 8.2, but if you test on a real device using iOS 7.1, you will unfortunately notice that you will never pass through the else part of the code snippet.


的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

作為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類型。


使用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
nv-ios-version

博客:在運行時使用Version類獲取並比較iOS版本
獲取並在運行時將iOS版本與Version類進行比較


使用推薦的推薦方式...如果頭文件中沒有定義,您可以隨時使用所需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;
}

僅用於檢索操作系統版本字符串值:

[[UIDevice currentDevice] systemVersion]

嘗試這個

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

嘗試:

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示例:

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年之前幾乎沒有任何用處



我總是把這些保存在我的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)

有像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
 }

正如Apple官方文檔所建議的那樣:您可以使用NSObjCRuntime.h頭文件中的NSObjCRuntime.h

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

這用於在Xcode中檢查兼容的SDK版本,這是因為如果您有一個擁有不同Xcode版本的大型團隊或支持共享相同代碼的不同SDK的多個項目:

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
  //programming in iOS 8+ SDK here
#else
  //programming in lower than iOS 8 here   
#endif

你真正想要的是檢查設備上的iOS版本。 你可以這樣做:

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

Swift版本:

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
}

#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
}       

#define _kisiOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)

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

/*
 *  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")) {
    ...
}

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




objective-c