[iphone] How can we programmatically detect which iOS version is device running on?

I want to check if the user is running the app on iOS less than 5.0 and display a label in the app.

How do I detect which iOS is running on user's device programmatically?

Thanks!

This question is related to iphone objective-c ios cocoa-touch ios4

The answer is


Marek Sebera's is great most of the time, but if you're like me and find that you need to check the iOS version frequently, you don't want to constantly run a macro in memory because you'll experience a very slight slowdown, especially on older devices.

Instead, you want to compute the iOS version as a float once and store it somewhere. In my case, I have a GlobalVariables singleton class that I use to check the iOS version in my code using code like this:

if ([GlobalVariables sharedVariables].iOSVersion >= 6.0f) {
    // do something if iOS is 6.0 or greater
}

To enable this functionality in your app, use this code (for iOS 5+ using ARC):

GlobalVariables.h:

@interface GlobalVariables : NSObject

@property (nonatomic) CGFloat iOSVersion;

    + (GlobalVariables *)sharedVariables;

@end

GlobalVariables.m:

@implementation GlobalVariables

@synthesize iOSVersion;

+ (GlobalVariables *)sharedVariables {
    // set up the global variables as a static object
    static GlobalVariables *globalVariables = nil;
    // check if global variables exist
    if (globalVariables == nil) {
        // if no, create the global variables class
        globalVariables = [[GlobalVariables alloc] init];
        // get system version
        NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
        // separate system version by periods
        NSArray *systemVersionComponents = [systemVersion componentsSeparatedByString:@"."];
        // set ios version
        globalVariables.iOSVersion = [[NSString stringWithFormat:@"%01d.%02d%02d", \
                                       systemVersionComponents.count < 1 ? 0 : \
                                       [[systemVersionComponents objectAtIndex:0] integerValue], \
                                       systemVersionComponents.count < 2 ? 0 : \
                                       [[systemVersionComponents objectAtIndex:1] integerValue], \
                                       systemVersionComponents.count < 3 ? 0 : \
                                       [[systemVersionComponents objectAtIndex:2] integerValue] \
                                       ] floatValue];
    }
    // return singleton instance
    return globalVariables;
}

@end

Now you're able to easily check the iOS version without running macros constantly. Note in particular how I converted the [[UIDevice currentDevice] systemVersion] NSString to a CGFloat that is constantly accessible without using any of the improper methods many have already pointed out on this page. My approach assumes the version string is in the format n.nn.nn (allowing for later bits to be missing) and works for iOS5+. In testing, this approach runs much faster than constantly running the macro.

Hope this helps anyone experiencing the issue I had!


[[[UIDevice currentDevice] systemVersion] floatValue]

In MonoTouch:

To get the Major version use:

UIDevice.CurrentDevice.SystemVersion.Split('.')[0]

For minor version use:

UIDevice.CurrentDevice.SystemVersion.Split('.')[1]

Update

From iOS 8 we can use the new isOperatingSystemAtLeastVersion method on NSProcessInfo

   NSOperatingSystemVersion ios8_0_1 = (NSOperatingSystemVersion){8, 0, 1};
   if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:ios8_0_1]) {
      // iOS 8.0.1 and above logic
   } else {
      // iOS 8.0.0 and below logic
   }

Beware that this will crash on iOS 7, as the API didn't exist prior to iOS 8. If you're supporting iOS 7 and below, you can safely perform the check with

if ([NSProcessInfo instancesRespondToSelector:@selector(isOperatingSystemAtLeastVersion:)]) {
  // conditionally check for any version >= iOS 8 using 'isOperatingSystemAtLeastVersion'
} else {
  // we're on iOS 7 or below
}

Original answer iOS < 8

For the sake of completeness, here's an alternative approach proposed by Apple itself in the iOS 7 UI Transition Guide, which involves checking the Foundation Framework version.

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
   // Load resources for iOS 6.1 or earlier
} else {
   // Load resources for iOS 7 or later
}

To get more specific version number information with major and minor versions separated:

NSString* versionString = [UIDevice currentDevice].systemVersion;
NSArray* vN = [versionString componentsSeparatedByString:@"."];

The array vN will contain the major and minor versions as strings, but if you want to do comparisons, version numbers should be stored as numbers (ints). You can add this code to store them in the C-array* versionNumbers:

int versionNumbers[vN.count];
for (int i = 0; i < sizeof(versionNumbers)/sizeof(versionNumbers[0]); i++)
    versionNumbers[i] = [[vN objectAtIndex:i] integerValue];

* C-arrays used here for more concise syntax.


[[UIDevice currentDevice] systemVersion]

I know I am too late to answer this question. I am not sure does my method still working on low iOS versions (< 5.0):

NSString *platform = [UIDevice currentDevice].model;

NSLog(@"[UIDevice currentDevice].model: %@",platform);
NSLog(@"[UIDevice currentDevice].description: %@",[UIDevice currentDevice].description);
NSLog(@"[UIDevice currentDevice].localizedModel: %@",[UIDevice currentDevice].localizedModel);
NSLog(@"[UIDevice currentDevice].name: %@",[UIDevice currentDevice].name);
NSLog(@"[UIDevice currentDevice].systemVersion: %@",[UIDevice currentDevice].systemVersion);
NSLog(@"[UIDevice currentDevice].systemName: %@",[UIDevice currentDevice].systemName);

You can get these results:

[UIDevice currentDevice].model: iPhone
[UIDevice currentDevice].description: <UIDevice: 0x1cd75c70>
[UIDevice currentDevice].localizedModel: iPhone
[UIDevice currentDevice].name: Someones-iPhone002
[UIDevice currentDevice].systemVersion: 6.1.3
[UIDevice currentDevice].systemName: iPhone OS

A simple check for iOS version less than 5 (all versions):

if([[[UIDevice currentDevice] systemVersion] integerValue] < 5){
        // do something
};

[[UIDevice currentDevice] systemVersion];

or check the version like

You can get the below Macros from here.

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(IOS_VERSION_3_2_0))      
{

        UIImageView *background = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cs_lines_back.png"]] autorelease];
        theTableView.backgroundView = background;

}

Hope this helps


Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?

Examples related to ios4

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870> How can we programmatically detect which iOS version is device running on? Convert a string into an int Xcode Objective-C | iOS: delay function / NSTimer help? How can I use NSError in my iPhone App? What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications? How to keep an iPhone app running on background fully operational How do you use NSAttributedString? How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup