如何从模拟器中获取 Iphone 类型 (IOS)

How to get the Iphone type from simulator (IOS)

有很多解决方案可以找出应用程序在哪个设备上 运行。

iOS: How to determine the current iPhone/device model in Swift?

但是运行在模拟器中,我们只能检测到它是模拟器,而不能检测到是什么类型的模拟器(iphone5,6,6s等)

我们如何使用模拟器根据设备类型测试不同的逻辑? 或者我如何检测代码中模拟了哪个设备?

根据我找到的答案 here and here,我为您编写了这个 Swift 小函数:

func getPlatformNSString() {
    #if (arch(i386) || arch(x86_64)) && os(iOS)
        let DEVICE_IS_SIMULATOR = true
    #else
        let DEVICE_IS_SIMULATOR = false
    #endif

    var machineSwiftString : String = ""

    if DEVICE_IS_SIMULATOR == true
    {
        // this neat trick is found at http://kelan.io/2015/easier-getenv-in-swift/
        if let dir = NSProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
            machineSwiftString = dir
        }
    } else {
        var size : size_t = 0
        sysctlbyname("hw.machine", nil, &size, nil, 0)
        var machine = [CChar](count: Int(size), repeatedValue: 0)
        sysctlbyname("hw.machine", &machine, &size, nil, 0)
        machineSwiftString = String.fromCString(machine)!
    }

    print("machine is \(machineSwiftString)")
}

我得到的结果是 "iPhone8,2",它转换为 iPhone 6+,这是我的模拟器设置的。

There's open source code available that you can use that would convert strings like "iPhone8,2" to the proper iPhone model name.

如果您想消除使用“DEVICE_IS_SIMULATOR”魔法的编译器警告,here's a better solution in the form of a class

从 Xcode 9.4.1 开始,NSProcessInfo().environment 现在包含 "SIMULATOR_DEVICE_NAME" 的键。值类似于 "iPhone 8".

你也可以使用我的BDLocalizedDevicesModels框架一行代码获取名称。 在 Github.

上查看

它适用于Objective-C和Swift,可以帮助您获取真实设备或模拟器的设备名称。

更新的代码也适用于 M1 mac 并在最新的 Swift

中编译
    public func getModelName() -> String {
        var machineSwiftString : String = ""
        #if targetEnvironment(simulator)
            if let dir = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
                    machineSwiftString = dir
            }
        #else
            var size : size_t = 0
            sysctlbyname("hw.machine", nil, &size, nil, 0)
            var machine = [CChar](count: Int(size), repeatedValue: 0)
            sysctlbyname("hw.machine", &machine, &size, nil, 0)
            machineSwiftString = String.fromCString(machine)!
        #endif
        return machineSwiftString
    }