有没有办法在Swift中获得设备型号名称(iPhone 4S, iPhone 5, iPhone 5S等)?
我知道有一个名为UIDevice.currentDevice()的属性。模型,但它只返回设备类型(iPod touch, iPhone, iPad, iPhone模拟器等)。
我也知道在Objective-C中使用以下方法可以轻松完成:
#import <sys/utsname.h>
struct utsname systemInfo;
uname(&systemInfo);
NSString* deviceModel = [NSString stringWithCString:systemInfo.machine
encoding:NSUTF8StringEncoding];
但是我正在Swift中开发我的iPhone应用程序,所以有人可以帮助我用等效的方法在Swift中解决这个问题吗?
我最近在开发这个swift包:
https://github.com/EmilioOjeda/Device
我认为它的主要优点是代码生成的。所以每当一个新的Xcode版本发布时,我所要做的就是运行一个脚本并更新swift包。
代码生成是如何工作的?
它从Xcode的数据库(每个平台)读取并解析设备的数据,以识别正在运行的设备,并为其提供信息。
这是用法……
import Device
// or => 'import iPhoneOSDevice' <= iPhoneOS-only device data
// or => 'import tvOSDevice' <= tvOS-only device data
// A representation of the running device - it could be either actual or simulated.
let device = Device.current
// It is 'true' when running on a physical device.
_ = device.isDevice
// It is 'true' when running on a simulator instance.
_ = device.isSimulator
// It is 'true' when the device does not match either simulators or physical devices.
_ = device.isUnknown
// The identifier for the device.
// i.e.: 'iPhone15,3'
let id = device.id
// The known/commercial name of the device.
// i.e.: 'iPhone 14 Pro Max'
let model = device.model
下面是获取硬件字符串的代码,但是您需要比较这些硬件字符串才能知道它是哪个设备。我已经创建了一个类,包含几乎所有的设备字符串(我们保持字符串最新的新设备)。使用方便,请检查
吉hub /恶魔大师
Objective-C: GitHub/DeviceUtil
public func hardwareString() -> String {
var name: [Int32] = [CTL_HW, HW_MACHINE]
var size: Int = 2
sysctl(&name, 2, nil, &size, &name, 0)
var hw_machine = [CChar](count: Int(size), repeatedValue: 0)
sysctl(&name, 2, &hw_machine, &size, &name, 0)
let hardware: String = String.fromCString(hw_machine)!
return hardware
}