Nice programing

iOS 버전은 어떻게 확인하나요?

nicepro 2020. 9. 28. 10:06
반응형

iOS 버전은 어떻게 확인하나요?


iOS장치 버전이 3.1.3내가 시도한 것 보다 큰지 확인하고 싶습니다.

[[UIDevice currentDevice].systemVersion floatValue]

하지만 작동하지 않습니다.

if (version > 3.1.3) { }

이것을 어떻게 할 수 있습니까?


빠른 답변…


Swift 2.0부터는 특정 시스템에서만 실행되어야하는 코드를 보호하기 위해 또는 #available에서 사용할 수 있습니다 .ifguard

if #available(iOS 9, *) {}


Objective-C에서는 시스템 버전을 확인하고 비교를 수행해야합니다.

[[NSProcessInfo processInfo] operatingSystemVersion] iOS 8 이상.

Xcode 9 기준 :

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


전체 답변…

Objective-C 및 Swift에서는 드물게 기기 또는 OS 기능의 표시로 운영 체제 버전에 의존하지 않는 것이 좋습니다. 일반적으로 특정 기능 또는 클래스를 사용할 수 있는지 여부를 확인하는 더 안정적인 방법이 있습니다.

API의 존재 확인 :

예를 들어 다음을 UIPopoverController사용하여 현재 장치에서 사용 가능한지 확인할 수 있습니다 NSClassFromString.

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

약하게 연결된 클래스의 경우 클래스에 직접 메시지를 보내는 것이 안전합니다. 특히 "필수"로 명시 적으로 링크되지 않은 프레임 워크에서 작동합니다. 누락 된 클래스의 경우 표현식은 nil로 평가되어 조건이 실패합니다.

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

일부 클래스는, 같은 CLLocationManagerUIDevice, 검사 장치 기능에 방법을 제공합니다 :

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

기호 유무 확인 :

아주 가끔 상수가 있는지 확인해야합니다. 이것은의 도입으로 아이폰 OS 8에 와서 UIApplicationOpenSettingsURLString설정 응용 프로그램을 통해로드하는 데 사용 -openURL:. 이 값은 iOS 8 이전에는 존재하지 않았습니다.이 API에 nil을 전달하면 충돌이 발생하므로 먼저 상수가 있는지 확인해야합니다.

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

운영 체제 버전과 비교 :

운영 체제 버전을 확인할 필요가 비교적 드물다고 가정 해 보겠습니다. iOS 8 이상을 대상으로하는 프로젝트 NSProcessInfo의 경우 오류 가능성이 적은 버전 비교를 수행하는 방법이 포함됩니다.

- (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version

이전 시스템을 대상으로 프로젝트를 사용할 수 있습니다 systemVersionUIDevice. 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).


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

공식 Apple 문서 에서 제안한대로 헤더 파일 NSFoundationVersionNumber에서,를 사용할 수 있습니다 NSObjCRuntime.h.

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

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 11iOS 11.0같은 최소한의 버전입니다
  • iOS 10, iOS 10.3은 ( iOS 10.3.1는) 다른 최소 버전입니다.

이러한 시스템에 대한 값을 입력 할 수 있습니다.

  • iOS, macOS, watchOS,tvOS

내 포드 중 하나 에서 가져온 실제 사례 :

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

선적 서류 비치


이것은 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
}

현재 버전의 swift는 다음을 사용해야합니다.

if #available(iOS 12, *) {
    //iOS 12 specific code here
} else {
    //older than iOS 12 code here
}

시험:

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
}

선호하는 접근 방식

스위프트 2.0에서 애플은 가용성이 훨씬 더 편리한 구문 (더 읽기 사용 검사를 추가 여기를 ). 이제 더 깨끗한 구문으로 OS 버전을 확인할 수 있습니다.

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

이것은 respondsToSelectoretc ( What 's New In Swift ) 를 확인하는 것보다 선호 됩니다. 이제 컴파일러는 코드를 제대로 보호하지 않으면 항상 경고합니다.


Pre 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에 배포

최소 전개 대상의 경우 아이폰 OS 7.1 이하 또는 비교 사용하십시오 NSStringCompareOptions.NumericSearchUIDevice systemVersion.

이것은 다음을 산출합니다.

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)

+(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 License, Version 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

블로그 : Version 클래스를
사용하여 런타임에 iOS 버전 가져 오기 및 비교 런타임에 Version 클래스를 사용하여 iOS 버전 가져 오기 및 비교


신속한 Forget [[UIDevice currentDevice] systemVersion] 및 NSFoundationVersionNumber를 사용하여 시스템 버전을 확인하는 새로운 방법입니다.

NSProcessInfo -isOperatingSystemAtLeastVersion을 사용할 수 있습니다.

     import Foundation

     let yosemite = NSOperatingSystemVersion(majorVersion: 10, minorVersion: 10, patchVersion: 0)
     NSProcessInfo().isOperatingSystemAtLeastVersion(yosemite) // false

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.0" compare:@"5" options:NSNumericSearch]반품 NSOrderedDescending이 가능 하므로 여기에서 약간주의해야 합니다. NSOrderedSame여기서 기대할 수 있습니다. 이것은 적어도 이론적 인 문제이며, 제 생각에는 방어 할 가치가 있습니다.

또한 고려할 가치가있는 것은 합리적으로 비교할 수없는 잘못된 버전 입력의 가능성입니다. 애플은 세 개의 미리 정의 된 상수를 공급 NSOrderedAscending, NSOrderedSame그리고 NSOrderedDescending하지만 난라는 어떤 것을 위해 사용 생각할 수있는 NSOrderedUnordered내가 두 가지 일을하지 비교할 수 나는 이것을 나타내는 값을 반환 할 경우에.

더욱이, 애플이 언젠가 세 가지 미리 정의 된 상수를 확장하여 다양한 반환 값을 허용하여 비교를 != 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 또는 이전 버전을 실행 중인지 테스트 할 때 많이 사용될 것입니다.


파티에 조금 늦었지만 iOS 8.0에 비추어 볼 때 관련성이있을 수 있습니다.

사용을 피할 수 있다면

[[UIDevice currentDevice] systemVersion]

대신 메서드 / 클래스 / 다른 것이 있는지 확인하십시오.

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

iOS 8.0 용 requestWhenInUseAuthorization을 호출해야하는 위치 관리자에 유용하지만 iOS <8에서는 메서드를 사용할 수 없습니다.


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

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

나는 이것이 오래된 질문이라는 것을 알고 있지만 누군가가 Availability.h. 여기에있는 다른 모든 메서드는 런타임 솔루션이며 헤더 파일, 클래스 범주 또는 ivar 정의에서 작동하지 않습니다.

이러한 상황에서는

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

h / t 대답


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

아래 코드를 시도하십시오.

NSString *versionString = [[UIDevice currentDevice] systemVersion];

OS 버전 문자열 값을 검색하기 위해 :

[[UIDevice currentDevice] systemVersion]

yasimturks 솔루션의 변형으로 5 개의 매크로 대신 하나의 함수와 몇 개의 열거 형 값을 정의했습니다. 나는 그것이 더 우아하다고 생각하지만 그것은 취향의 문제입니다.

용법:

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

이 솔루션의 단점 : 어떤 방식 으로든 OS 버전 번호를 확인하는 것은 나쁜 습관입니다. 이런 식으로 종속성을 하드 코딩해서는 안되며, 항상 기능, 기능 또는 클래스의 존재를 확인해야합니다. 이걸 고려하세요; Apple은 이전 버전과 호환되는 클래스 버전을 출시 할 수 있습니다. 만약 그렇다면 여러분이 제안한 코드는 클래스의 존재가 아닌 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을 사용하는 실제 장치에서 테스트하는 경우 불행히도 코드 조각의 다른 부분을 통과하지 않을 것임을 알 수 있습니다.


#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

실제로 작동하는 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
}

참고 URL : https://stackoverflow.com/questions/3339722/how-to-check-ios-version

반응형