如何从模拟器(IOS)获取Iphone类型 [英] How to get the Iphone type from simulator (IOS)

查看:587
本文介绍了如何从模拟器(IOS)获取Iphone类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多解决方案可以找出正在运行的设备。



iOS:如何确定Swift中当前的iPhone /设备型号?



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



怎么能我们根据模拟器的设备类型测试不同的逻辑?
或者如何检测代码中模拟的设备?

解决方案

根据我找到的答案这里这里,我为你写了这个小Swift函数:

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

var machineSwiftString:String =

如果DEVICE_IS_SIMULATOR == true
{
//这个巧妙的技巧可以在http://kelan.io/2015/easier-getenv-in-swift/
找到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,& ;机器,& size,nil,0)
machineSwiftString = String.fromCString(机器)!
}

print(machine is \(machineSwiftString))
}

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



有您可以使用的开源代码将 iPhone8,2 等字符串转换为正确的iPhone型号名称



如果你想摆脱使用 DEVICE_IS_SIMULATOR 魔法的编译器警告,这是一个更好的类形式的解决方案


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 ?

解决方案

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.

这篇关于如何从模拟器(IOS)获取Iphone类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆