使用Swift的sysctlbyname()

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (136)

我使用代码来确定哪个iOS设备(例如iPhone5,1)我的应用程序正在运行:

- (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 stringWithUTF8String:machine];
    free(machine);
    return platform;
}

C数据类型得到了很好的支持,但它并没有提到有关C函数的任何信息。有没有一种纯粹的Swift方法来检索机器标识符,还是必须为此连接到Objective-C?

提问于
用户回答回答于
func platform() -> String {
    var size : Int = 0 // as Ben Stahl noticed in his answer
    sysctlbyname("hw.machine", nil, &size, nil, 0)
    var machine = [CChar](count: size, repeatedValue: 0)
    sysctlbyname("hw.machine", &machine, &size, nil, 0)
    return String.fromCString(machine)!
}

SWIFT 3更新:

func platform() -> String {
    var size = 0
    sysctlbyname("hw.machine", nil, &size, nil, 0)
    var machine = [CChar](repeating: 0,  count: size)
    sysctlbyname("hw.machine", &machine, &size, nil, 0)
    return String(cString: machine)
}
用户回答回答于
func platformModelString() -> String? {
    if let key = "hw.machine".cString(using: String.Encoding.utf8) {
        var size: Int = 0
        sysctlbyname(key, nil, &size, nil, 0)
        var machine = [CChar](repeating: 0, count: Int(size))
        sysctlbyname(key, &machine, &size, nil, 0)
        return String(cString: machine)
    }
    return nil
}

扫码关注云+社区

领取腾讯云代金券