Clicky

iOS Dev Nugget 41 Checking if Newer APIs Are Available In Older iOS Versions

.

Need to run a code review on your codebase? Hire me

Sometimes you want to support older iOS versions and want to disable or hide a certain feature when it relies on APIs that are only available in newer iOS versions. In this case, you can't rely on conditional compilation since the same executable has to support multiple iOS versions.

You'll need to configure your project's deployment target to the oldest version of iOS you are supporting and at run time, check if the class or function exists and fall back to a different code path. For example, if you are supporting both iOS 5 and iOS 6 and want to make use of the class SKStoreProductViewController (which is only available in iOS 6 and newer), you'd write:

if ([SKStoreProductViewController class])) {
    // Class is supported
    SKStoreProductViewController *storeController = [[SKStoreProductViewController alloc] init];
    //Do something with it
} else {
    // Class not available. Unless the class is removed in future versions of iOS, this is likely iOS 5 or earlier
}

If a class doesn't support this check, you can fall back to this check instead:

if (NSClassFromString(@"SKStoreProductViewController")) {
} else {
}

You can do similar checks for methods and C functions with:

//Check if method is available
if ([UIImagePickerController instancesRespondToSelector:@selector(availableCaptureModesForCameraDevice:)]) {
} else {
}

//Check if function is available
if (UIGraphicsBeginImageContextWithOptions) {
} else {
}

See the SDK Compatibility Guide for more details.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues