有很多解决方案可以找出应用程序在哪个设备上运行。
iOS: How to determine the current iPhone/device model in Swift?
但是在模拟器中运行,只能检测到是模拟器,并不能检测到是什么类型的模拟器(iphone5,6,6s等)
我们如何使用模拟器根据设备类型测试不同的逻辑? 或者我如何检测代码中模拟了哪个设备?
最佳答案
根据我找到的答案here和 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+,这是我的模拟器设置的。
如果您想摆脱使用“DEVICE_IS_SIMULATOR
”魔法的编译器警告,here's a better solution in the form of a class .
关于ios - 如何从模拟器(IOS)获取Iphone类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33493800/