Determine user's device using iOS SDK and full Cocoa Touch / Objective-C code

拜拜、爱过 提交于 2019-12-03 00:22:28

This may be considered an "objective-c" way of doing it:

// Utility method (private)
- (NSString *)platformCode {
    // This may or not be necessary 
    // Im not sure if you can have a device thats not currentDevice can you?
    // if ([self isEqual:[UIDevice currentDevice]]) {

    NSString* platform =  [[self.systemName copy] autorelease];
    return platform;

    // Could probably shorten to just
    // return [[self.systemName copy] autorelease];

    // or - return [NSString stringWithString:self.systemName];
}

This would be obj-c version of utsname machine (from this line: NSString* platform =  [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];).

utsname:

The <sys/utsname.h> header defines structure utsname, which includes at least the following members:

char sysname[]   name of this implementation of the operating system
char nodename[] name of this node within an implementation-dependent communications network
char release[]   current release level of this implementation
char version[]   current version level of this release
char machine[]   name of the hardware type on which the system is running

UIDevice Class Reference:

systemName The name of the operating system running on the device represented by the receiver. (read-only)
@property (nonatomic, readonly, retain) NSString *system


But, since systemName only returns @"iPhone OS", to get the actual device model number, you have to use c code. Here's another way to do it:

#include <sys/types.h>
#include <sys/sysctl.h>

- (NSString *)machine {
     size_t size;

    // Set 'oldp' parameter to NULL to get the size of the data
    // returned so we can allocate appropriate amount of space
    sysctlbyname("hw.machine", NULL, &size, NULL, 0); 

    // Allocate the space to store name
    char *name = malloc(size);

    // Get the platform name
    sysctlbyname("hw.machine", name, &size, NULL, 0);

    // Place name into a string
    NSString *machine = [NSString stringWithCString:name];

    // Done with this
    free(name);

    return machine;
}

You'll have to use the low level C call to get the infoString. For my purposes I've written a tiny Objective-C library that abstracts this away and presents an Objective-C interface.

NSLog(@"Big model number: %d", deviceDetails.bigModel);
//Big model number: 4

NSLog(@"Small model number: %d", deviceDetails.smallModel);
//Small model number: 1

if (deviceDetails.model == GBDeviceModeliPhone4S) {
    NSLog(@"It's a 4S");
}
//It's a 4S

if (deviceDetails.family != GBDeviceFamilyiPad) {
    NSLog(@"It's not an iPad");
}
//It's not an iPad

NSLog(@"systemInfo string: %@", [GBDeviceInfo rawSystemInfoString]);
//systemInfo string: iPhone4,1

You can get it on github if you like: GBDeviceInfo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!