下面的代码应该显示运行应用程序的设备的型号/设备名称。例如,如果应用程序在第一代iPod上运行,我希望它显示“iPod1,1”。当我运行应用程序时,标签为空。我做错了什么?
#import "ViewController.h"
#include <sys/types.h>
#include <sys/sysctl.h>
@interface ViewController ()
@end
@implementation ViewController
@synthesize label;
- (void)viewDidLoad
{
label.text = [self platformString];
[self platformCapabilities];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (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 encoding: NSUTF8StringEncoding];
free(machine);
return platform;
}
- (int) platformType
{
NSString *platform = [self platform];
if ([platform isEqualToString:@"iPhone1,1"]) return UIDevice1GiPhone;
if ([platform isEqualToString:@"iPhone1,2"]) return UIDevice3GiPhone;
if ([platform isEqualToString:@"iPod1,1"]) return UIDevice1GiPod;
if ([platform isEqualToString:@"iPod2,1"]) return UIDevice2GiPod;
if ([platform hasPrefix:@"iPhone"]) return UIDeviceUnknowniPhone;
if ([platform hasPrefix:@"iPod"]) return UIDeviceUnknowniPod;
return UIDeviceUnknown;
}
- (NSString *) platformString
{
switch ([self platformType])
{
case UIDevice1GiPhone: return IPHONE_1G_NAMESTRING;
case UIDevice3GiPhone: return IPHONE_3G_NAMESTRING;
case UIDeviceUnknowniPhone: return IPHONE_UNKNOWN_NAMESTRING;
case UIDevice1GiPod: return IPOD_1G_NAMESTRING;
case UIDevice2GiPod: return IPOD_2G_NAMESTRING;
case UIDeviceUnknowniPod: return IPOD_UNKNOWN_NAMESTRING;
default: return nil;
}
}
- (int) platformCapabilities
{
switch ([self platformType])
{
case UIDevice1GiPhone: return UIDeviceBuiltInSpeaker | UIDeviceBuiltInCamera | UIDeviceBuiltInMicrophone | UIDeviceSupportsExternalMicrophone | UIDeviceSupportsTelephony | UIDeviceSupportsVibration;
case UIDevice3GiPhone: return UIDeviceSupportsGPS | UIDeviceBuiltInSpeaker | UIDeviceBuiltInCamera | UIDeviceBuiltInMicrophone | UIDeviceSupportsExternalMicrophone | UIDeviceSupportsTelephony | UIDeviceSupportsVibration;
case UIDeviceUnknowniPhone: return UIDeviceBuiltInSpeaker | UIDeviceBuiltInCamera | UIDeviceBuiltInMicrophone | UIDeviceSupportsExternalMicrophone | UIDeviceSupportsTelephony | UIDeviceSupportsVibration;
case UIDevice1GiPod: return 0;
case UIDevice2GiPod: return UIDeviceBuiltInSpeaker | UIDeviceBuiltInMicrophone | UIDeviceSupportsExternalMicrophone;
case UIDeviceUnknowniPod: return 0;
default: return 0;
}
}
@end
另外,我如何扩展此代码以识别第三代iPod,第四代iPod等?
答案 0 :(得分:0)
我建议使用Erica的UIDevice-Extensions类别来实现您的目标。
https://github.com/erica/uidevice-extension
对于您的应用运行的设备类型,几乎所有类型的内省都有代码。
答案 1 :(得分:0)
你必须打你的零。您是否尝试使用平台方法查看它返回的内容以及是否与您的任何案例相匹配?