How to get iOS version programatically?

Answer

The iOS version can be found out simply using the following command

[UIDevice currentDevice] systemVersion]

New iOS API are added every release of iOS. That means certain API are only available after a certain version and we want to make sure we check whether the iOS version of the phone running the application is greater than or less than a certain number/version before invoking the API calls. In such case we can use macros as:

#define IOS_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)

#define IOS_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)

#define IOS_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

#define IOS_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

#define IOS_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

 

Example in the below snippet we set the background property of UITableView to an image only if iOS version >= 3.2.0 as this property was added in that release itself.

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