Monday, December 20, 2010

How to Detect iOS Version in Code

Bumbed into a case where code crashed iOS 4.0.2, but worked with iOS 4.2. Since crash happened because of missing NSString *const, couldn't use respondsToSelector to choose, which code to run. Decided to simply check what is current iOS version:
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version > 4.0)
{
    // iOS 4.2 specific code
}
else
{
    // iOS 4.0.2 specific code
}
Please note how three part version number gets converted to float:
NSString *s = [[UIDevice currentDevice] systemVersion];
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
NSLog(@"Version: %@ and %f", s, version);
NSLog(@"Version: %@ and %f", @"3.1.3", [@"3.1.3" floatValue]);

Version: 4.0.2 and 4.000000
Version: 3.1.3 and 3.100000
I'm not really happy with the solution, but it works. Can live with that.

Update:

Always run code in real device! My development device iPhone4 with iOS 4.1 returns "4.1" as string, but that gives 4.0999999 as float value !!!

3 comments:

  1. I've written a post about how to properly detect iOS version. You can take a look here. http://formtools.tumblr.com/post/2080375589/detecting-ios-version

    ReplyDelete
  2. Also, useful is if you need the version data for pre-processor macros.

    #define __IPHONE_2_0 20000
    ...
    #define __IPHONE_4_2 40200

    For legacy support for things like...
    #ifdef __IPHONE_4_0
    @interface YOURCLASS : NSObject
    #else
    @interface YOURCLASS : NSObject
    #endif

    ReplyDelete
  3. Text comparision can be useful, true. Depends how reliable comparision is, had some problems with it http://stackoverflow.com/questions/3861447/problem-using-nsstring-compareoptionsrange-conflicting-results

    Pre-processor macros are useful, when you need to decide at application build time which code to take. Not so helpful, when you need to run same app (binary) in several incompatible iOS versions.

    Thanx for comments!

    ReplyDelete