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

标签 ios swift ios-simulator device

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

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

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

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

最佳答案

根据我找到的答案herehere ,我为您编写了这个 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 .

关于ios - 如何从模拟器(IOS)获取Iphone类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33493800/

相关文章:

xcode - Xcode/Simulator 占用 15gb 空间是否正常?

ios - Xcode 7.1 运行目的地列表中的通用 iOS 设备是什么?

ios - 将 PDF 传递给 UIActivityViewController

ios - swift中的行控制语句

node.js - 类型错误 : Cannot read property 'save' of null

ios - 我们可以为具有动态高度的 UITableViewCell 使用 XIB 吗?

xcode - MonoTouch 应用程序构建

ios - ARKit 无摄像头 - XCode

iphone - MPMoviePlayerController 上的专辑封面

ios - 在 iphone 5 中调整相机表的大小