How does one get UI_USER_INTERFACE_IDIOM() to work with iPhone OS SDK < 3.2

drootang picture drootang · Apr 5, 2010 · Viewed 39.9k times · Source

Apple advises using the following code to detect whether running on an iPad or iPhone/iPod Touch:

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  // The device is an iPad running iPhone 3.2 or later.
  // [for example, load appropriate iPad nib file]
}
else {
  // The device is an iPhone or iPod touch.
  // [for example, load appropriate iPhone nib file]
}

The problem is that UI_USER_INTERFACE_IDIOM() and UIUserInterfaceIdiomPad are NOT defined in the SDKs prior to 3.2. This seems to completely defeat the purpose of such a function. They can only be compiled and run on iPhone OS 3.2 (iPhone OS 3.2 can only be run on iPad). So if you can use UI_USER_INTERFACE_IDIOM(), the result will always be to indicate an iPad.

If you include this code and target OS 3.1.3 (the most recent iPhone/iPod Touch OS) in order to test your iPhone-bound universal app code, you will get compiler errors since the symbols are not defined in 3.1.3 or earlier, when compiling for iPhone simulator 3.1.3.

If this is the recommended-by-Apple approach to runtime device-detection, what am I doing wrong? Has anyone succeeded using this approach to device-detection?

Answer

Sangraal picture Sangraal · Apr 9, 2010

I do this to get the code to compile in both 3.1.3 and 3.2:

BOOL iPad = NO;
#ifdef UI_USER_INTERFACE_IDIOM
iPad = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);
#endif
if (iPad) {
// iPad specific code here
} else {
// iPhone/iPod specific code here
}

I also wrote a quick blog post about it here: http://www.programbles.com/2010/04/03/compiling-conditional-code-in-universal-iphone-ipad-applications/