How to get the Iphone type from simulator (IOS)

一笑奈何 提交于 2019-11-26 21:15:24

问题


There are a lot of solutions to find out on which device out app is running.

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

But running in the simulator, we just can detect that it is the simulator, but not what type of simulator (iphone5,6,6s etc.)

How can we test different logics depending on devicetype with the simulator ? Or how can I detect which device is simulated in code ?


回答1:


Based on the answers I found here and here, I wrote this little Swift function for you:

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)")
}

I'm getting a result of "iPhone8,2", which converts to an iPhone 6+, which is what my simulator is set to.

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

And if you want to get rid of the compiler warning for using the "DEVICE_IS_SIMULATOR" magic, here's a better solution in the form of a class.




回答2:


As of Xcode 9.4.1, NSProcessInfo().environment now includes a key for "SIMULATOR_DEVICE_NAME". Values look like "iPhone 8".




回答3:


You can also use my BDLocalizedDevicesModels framework to get the name in one line of code. Check it on Github.

It works with Objective-C and Swift and can help you to get the device name for real device or simulator.



来源:https://stackoverflow.com/questions/33493800/how-to-get-the-iphone-type-from-simulator-ios

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