有很多解决方案可以找出运行在哪个设备上的out应用程序。
iOS: How to determine the current iPhone/device model in Swift?
但是在模拟器中运行,我们只能检测到它是模拟器,而不是什么类型的模拟器(iphone5,6,6s等)。
如何使用模拟器根据设备类型测试不同的逻辑?或者,我如何检测哪个设备是用代码模拟的?
发布于 2015-11-03 17:45:57
基于我找到的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。
发布于 2018-06-28 05:40:12
从Xcode9.4.1开始,NSProcessInfo().environment现在包含一个用于"SIMULATOR_DEVICE_NAME“的键。值看起来像"iPhone 8“。
发布于 2018-09-04 04:47:59
您还可以使用我的BDLocalizedDevicesModels框架在一行代码中获取名称。在Github上查一下。
它与Objective-C和Swift配合使用,可以帮助您获取真实设备或模拟器的设备名称。
https://stackoverflow.com/questions/33493800
复制相似问题