Jak sprawdzić wersję iOS?

Chcę sprawdzić czy wersja iOS urządzenia jest większa niż 3.1.3 Próbowałem takich rzeczy jak:

[[UIDevice currentDevice].systemVersion floatValue]

Ale to nie działa, chcę tylko:

if (version > 3.1.3) { }

Jak mogę to osiągnąć?

Author: James Webster, 2010-07-27

30 answers

Szybka odpowiedź ...


Począwszy od Swift 2.0, możesz użyć #available W if lub guard do ochrony kodu, który powinien być uruchamiany tylko na niektórych systemach.

if #available(iOS 9, *) {}


W Objective-C należy sprawdzić wersję systemu i przeprowadzić porównanie.

[[NSProcessInfo processInfo] operatingSystemVersion] W iOS 8 i nowszych.

Od Xcode 9:

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


Pełna odpowiedź ...

W Objective-C, a w rzadkich przypadkach Swift, lepiej unikać poleganie na wersji systemu operacyjnego jako wskazanie możliwości urządzenia lub systemu operacyjnego. Zazwyczaj istnieje bardziej niezawodna metoda sprawdzania, czy dana funkcja lub klasa jest dostępna.

Sprawdzanie obecności API:

Na przykład, możesz sprawdzić, czy UIPopoverController jest dostępny na bieżącym urządzeniu za pomocą NSClassFromString:

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

Dla klas słabo powiązanych, bezpiecznie jest wysłać wiadomość bezpośrednio do klasy. Co ważne, działa to w przypadku frameworków, które nie są wyraźnie linked as "Required": True, W przypadku brakujących klas wyrażenie jest ewaluowane do nil, nie spełniając warunku:

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

Niektóre klasy, takie jak CLLocationManager i UIDevice, dostarczają metod sprawdzania możliwości urządzenia:

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

Sprawdzanie obecności symboli:

Bardzo sporadycznie, musisz sprawdzić obecność stałej. W systemie iOS 8 pojawiła się funkcja UIApplicationOpenSettingsURLString, używana do ładowania aplikacji ustawień za pomocą -openURL:. Wartość nie istniała przed iOS 8. Podanie nil do ten API ulegnie awarii, więc musisz najpierw zweryfikować istnienie stałej:

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

Porównanie z wersją systemu operacyjnego:

Załóżmy, że masz do czynienia ze stosunkowo rzadką potrzebą sprawdzenia wersji systemu operacyjnego. W przypadku projektów skierowanych na system iOS 8 i nowsze, NSProcessInfo zawiera metodę porównywania wersji z mniejszą szansą na błąd.]}

- (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version

Projekty ukierunkowane na starsze systemy mogą używać systemVersion na UIDevice. Apple go używa w ich GLSprite przykładowy kod.

// 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;
}

Jeśli z jakiegokolwiek powodu zdecydujesz, że systemVersion jest tym, czego chcesz, traktuj to jako ciąg znaków, w przeciwnym razie ryzykujesz skrócenie numeru wersji poprawki (np. 3.1.2 -> 3.1).

 920
Author: Justin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-06 15:14:35
/*
 *  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")) {
    ...
}
 1040
Author: yasirmturk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-17 10:28:43

Zgodnie z sugestią official Apple docs : możesz użyć NSFoundationVersionNumber, z pliku nagłówkowego NSObjCRuntime.h.

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    // here you go with iOS 7
}
 246
Author: CarlJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-28 13:09:56

Począwszy od Xcode 9, w Objective-C :

if (@available(iOS 11, *)) {
    // iOS 11 (or newer) ObjC code
} else {
    // iOS 10 or older code
}

Począwszy od Xcode 7, w Swift :

if #available(iOS 11, *) {
    // iOS 11 (or newer) Swift code
} else {
    // iOS 10 or older code
}

Dla wersji można określić dur, moll lub PATCH (zobacz http://semver.org / dla definicji). Przykłady:

  • iOS 11 i iOS 11.0 są tą samą minimalną wersją
  • iOS 10, iOS 10.3, iOS 10.3.1 są różne wersje Minimalne

Możesz wprowadzić wartości dla każdego z tych systemy:

  • iOS, macOS, watchOS, tvOS

Przykład prawdziwego przypadku wzięty z jednej z moich strąków :

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

Dokumentacja

 69
Author: Cœur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-21 11:11:44

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
}
 36
Author: Jonathan Grynspan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-26 23:33:07

Jest to używane do sprawdzania kompatybilnej wersji SDK w Xcode, jeśli masz duży zespół z różnymi wersjami Xcode lub wiele projektów obsługujących różne zestawy SDK, które mają ten sam kod:

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

Naprawdę chcesz sprawdzić wersję iOS na urządzeniu. Możesz to zrobić za pomocą tego:

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

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

Aktualne wersje swift powinny używać tego:

if #available(iOS 12, *) {
    //iOS 12 specific code here
} else {
    //older than iOS 12 code here
}
 35
Author: Travis M.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-25 21:42:21

Preferowane Podejście

W Swift 2.0 Apple dodało sprawdzanie dostępności za pomocą znacznie wygodniejszej składni (Czytaj więcej tutaj ). Teraz możesz sprawdzić wersję systemu operacyjnego z czystszą składnią:

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

To jest preferowane przez sprawdzanie respondsToSelector etc (Co nowego w Swift ). Teraz kompilator zawsze cię ostrzega, jeśli nie pilnujesz poprawnie kodu.


Pre Swift 2.0

Nowy w iOS 8 jest NSProcessInfo pozwalający na lepszą wersjonowanie semantyczne czeki.

W tym celu należy skontaktować się z działem obsługi klienta.]}
W przypadku systemu iOS 8.0 (30) lub nowszego, użyj aplikacji NSProcessInfo operatingSystemVersion lub isOperatingSystemAtLeastVersion.

Daje to następujące:

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)
}
W tym celu należy skontaktować się z działem obsługi klienta.]}

Dla minimalnych celów wdrożenia iOS 7.1 lub poniżej, użyj porównaj z NSStringCompareOptions.NumericSearch on UIDevice systemVersion.

To daje:

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

Więcej na NSHipster .

 34
Author: Daniel Galasko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-02 13:06:00

Polecam:

if ([[[UIDevice currentDevice] systemVersion] floatValue] > 3.13) {
    ; // ...
}

Kredyt: Jak wybrać konkretną wersję iPhone ' a?

 19
Author: ohho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:32

Zawsze trzymam je w stałych.plik 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)
 8
Author: Segev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-15 10:10:33
+(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;
  }


}
 6
Author: Jef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-20 12:59:52

Z klasą Version zawartą w projekcie NV-iOS-version (Licencja Apache, Wersja 2.0), łatwo jest uzyskać i porównać wersję iOS. Poniższy przykładowy kod zrzuca wersję iOS i sprawdza, czy wersja jest większa lub równa 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.
}

Strona projektu: nv-iOS-version
TakahikoKawasaki / nv-iOS-version

Blog: Pobierz i porównaj wersję systemu iOS w środowisku wykonawczym z klasą wersji
Pobierz i porównaj iOS wersja w środowisku runtime z klasą wersji

 6
Author: Takahiko Kawasaki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-28 09:56:52

Nowy sposób sprawdzania wersji systemu za pomocą swift Forget [[UIDevice currentDevice] systemVersion] i NSFoundationVersionNumber.

Możemy użyć NSProcessInfo-isoperatingsystemleastversion

     import Foundation

     let yosemite = NSOperatingSystemVersion(majorVersion: 10, minorVersion: 10, patchVersion: 0)
     NSProcessInfo().isOperatingSystemAtLeastVersion(yosemite) // false
 5
Author: iGo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-11 09:02:35

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
 5
Author: Oliver Pearmain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-07 09:31:59

Ogólnie rzecz biorąc lepiej jest zapytać, czy obiekt może wykonać dany selektor, niż sprawdzać numer wersji, aby zdecydować, czy musi być obecny.

Jeśli nie jest to opcja, musisz być trochę ostrożny, ponieważ [@"5.0" compare:@"5" options:NSNumericSearch] zwraca NSOrderedDescending, które mogą nie być w ogóle zamierzone; mogę się spodziewać NSOrderedSame tutaj. Jest to przynajmniej teoretyczna troska, przed którą moim zdaniem warto się bronić.

Warto również rozważyć możliwość wprowadzenia złej wersji, która nie można rozsądnie porównać. Apple dostarcza trzy predefiniowane stałe NSOrderedAscending, NSOrderedSame i NSOrderedDescending ale mogę pomyśleć o użyciu jakiejś rzeczy zwanej NSOrderedUnordered W przypadku, gdy nie mogę porównać dwóch rzeczy i chcę zwrócić wartość wskazującą to.

Co więcej, nie jest niemożliwe, aby Apple pewnego dnia rozszerzyło swoje trzy predefiniowane stałe, aby umożliwić różne wartości zwrotne, co czyni porównanie != NSOrderedAscending nierozsądnym.

Z tym powiedziane, rozważ następujący kod.

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
 4
Author: SK9,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-28 03:54:59
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
        // Your code here
}

Gdzie oczywiście, {[1] } musi zostać zmieniona na przez dotyczy wersji iOS, którą chcesz sprawdzić. To, co teraz napisałem, prawdopodobnie będzie dużo używane podczas testowania, czy urządzenie działa z iOS7 lub poprzednią wersją.

 4
Author: OscarWyck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-04 11:43:55

Trochę za późno na imprezę, ale w świetle iOS 8.0 to może być istotne:

Jeśli można uniknąć używania

[[UIDevice currentDevice] systemVersion]

Zamiast tego Sprawdź istnienie metody / klasy / cokolwiek innego.

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

Okazało się, że jest to przydatne dla menedżera lokalizacji, gdzie muszę wywołać requestWhenInUseAuthorization dla iOS 8.0, ale metoda nie jest dostępna dla iOS

 4
Author: Denis Kanygin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-23 23:46:31
#define _kisiOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)

if (_kisiOS7) {
            NSLog(@"iOS7 or greater")
} 
else {
           NSLog(@"Less than iOS7");
}
 3
Author: Gaurav Gilani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-17 11:19:16
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

Następnie Dodaj warunek if w następujący sposób: -

if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
   //Your code
}       
 3
Author: Sumit Kumar Saha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-08 14:15:13

Istnieją wersje takie jak 7.0 lub 6.0.3, więc możemy po prostu przekonwertować wersję na liczby do porównania. jeśli wersja jest jak 7.0, po prostu dołączyć inny".0" do niego, a następnie pobrać jego wartość liczbową.

 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];

Dla 6.0.0

  if (version==600) {
    // Do something
  }

Dla 7.0

 if (version==700) {
   // Do something
 }
 2
Author: NaXir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-11 10:05:21

Wypróbuj poniższy kod:

NSString *versionString = [[UIDevice currentDevice] systemVersion];
 2
Author: annu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-08 06:54:27

Tylko do pobierania wartości ciągu wersji systemu operacyjnego:

[[UIDevice currentDevice] systemVersion]
 2
Author: Javier Calatrava Llavería,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-12 10:29:23

Jako wariant rozwiązania yasimturks zdefiniowałem jedną funkcję i kilka wartości enum zamiast pięciu makr. Uważam, że jest bardziej elegancki, ale to kwestia gustu.

Użycie:

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

.plik h:

typedef enum {
  LessThan,
  LessOrEqual,
  Equal,
  GreaterOrEqual,
  GreaterThan,
  NotEqual
} Comparison;

BOOL systemVersion(Comparison test, NSString* version);

.plik 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;
  }
}

Należy dodać prefiks aplikacji do nazw, szczególnie do typu Comparison.

 1
Author: jcsahnwaldt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-07 17:47:30

Wiem, że to stare pytanie, ale ktoś powinien był wspomnieć o makrach kompilowanych w Availability.h. Wszystkie pozostałe metody są rozwiązaniami uruchomieniowymi i nie będą działać w pliku nagłówkowym, kategorii klas lub definicji ivar.

W takich sytuacjach użyj

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
  // iOS 6+ code here
#else
  // Pre iOS 6 code here
#endif

H/t this answer

 1
Author: bcattle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:34

Używając zalecanego sposobu... jeśli w plikach nagłówkowych nie ma definicji, zawsze możesz wydrukować wersję na konsoli za pomocą urządzenia o żądanej wersji 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;
}
 1
Author: tyoc213,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-02 16:20:27

Rozwiązanie do sprawdzania wersji iOS w języku Swift

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

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

Błąd tego rozwiązania: sprawdzanie numerów wersji systemu operacyjnego jest po prostu złą praktyką, niezależnie od tego, w jaki sposób to zrobisz. Nigdy nie należy w ten sposób kodować zależności, zawsze sprawdzać, czy istnieją cechy, możliwości lub istnienie klasy. Rozważ to; Apple może wydać wstecznie kompatybilną wersję klasy, jeśli tak się stanie, kod, który sugerujesz, nigdy nie użyłby jej, ponieważ twoja logika szuka numeru wersji systemu operacyjnego, a nie istnienie klasy.

(źródło tej informacji )

Rozwiązanie do sprawdzania istnienia klasy w języku Swift

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

Nie używaj if (NSClassFromString("UIAlertController") == nil), ponieważ działa poprawnie na symulatorze iOS z iOS 7.1 i 8.2, ale jeśli przetestujesz na prawdziwym urządzeniu z iOS 7.1, niestety zauważysz, że nigdy nie przejdziesz przez inną część fragmentu kodu.

 1
Author: King-Wizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-05 11:11:15
#define IsIOS8 (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
 1
Author: Gank,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-30 09:48:28

Bardziej ogólna wersja w Obj-C++ 11 (prawdopodobnie możesz zastąpić niektóre z tych rzeczy funkcjami NSString/C, ale jest to mniej gadatliwe. To daje dwa mechanizmy. splitSystemVersion daje Ci tablicę wszystkich części, która jest przydatna, jeśli chcesz tylko włączyć główną wersję (np. 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;
}
 0
Author: Vitali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-30 03:58:00

Spróbuj tego

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) { 
// do some work
}
 0
Author: Muhammad Aamir Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-03 13:32:09
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
 0
Author: GJDK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-12 13:19:01

Szybki przykład, który faktycznie działa:

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

Nie używaj NSProcessInfo ponieważ nie działa pod 8.0, więc jest prawie bezużyteczny aż do 2016

 0
Author: Esqarrouth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-08 13:29:34