views:

251

answers:

2

How do I detect if a user is running the application on an iPhone 4 or 3G/3GS?

I need to detect the hardware, not the iOS version.

thanks for any help.

+2  A: 

You can call currentDevice on UIDevice and look at the model property.

Edit: Although... the docs suggest this doesn't include the exact model number.

Joost Schuur
+5  A: 

feel free to use this class - I found it here

Usage

UIDeviceHardware *h=[[UIDeviceHardware alloc] init];
[self setDeviceModel:[h platformString]];   
[h release];

UIDeviceHardware.h

//
//  UIDeviceHardware.h
//
//  Used to determine EXACT version of device software is running on.

#import <Foundation/Foundation.h>

@interface UIDeviceHardware : NSObject 

- (NSString *) platform;
- (NSString *) platformString;

@end

UIDeviceHardware.m

//
//  UIDeviceHardware.m
//
//  Used to determine EXACT version of device software is running on.

#import "UIDeviceHardware.h"
#include <sys/types.h>
#include <sys/sysctl.h>

@implementation UIDeviceHardware

- (NSString *) platform{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine];
    free(machine);
    return platform;
}

- (NSString *) platformString{
    NSString *platform = [self platform];
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G";
    if ([platform isEqualToString:@"i386"])   return @"iPhone Simulator";
    return platform;
}

@end
SeniorShizzle
Much better than my answer, but someone needs to run this on an iPhone 4 and see what the machine string is for that model.I think it might be "iPhone3,1".
Joost Schuur
+1 Good point. I'm too tired now, but I'll try tomorrow and post the results-- unless anybody beats me to it
SeniorShizzle
I'd just use hw.machine (and hw.model). iPhone1,1 is also known as "Original iPhone" or "iPhone 2G" (unofficialy) and Apple lists "iPod Touch 2nd generation" and "iPod Touch 3rd generation", one of which is missing here (presumably iPod2,2)
tc.
and what about the iPad? and this method fails to detect the correct version of the simulator. Any clues?
Digital Robot
iPhone 4 = "iPhone3,1"
Stephen
It's a bit laborious, but <http://www.everymac.com/> has the platform strings listed for each iOS device. For example, <http://www.everymac.com/systems/apple/consumer_electronics/stats/ipod-touch-4th-gen-4g-facetime-specs.html> for iPod touch 4th gen. I have not been able to find a list indexed on platform string.
westsider