How to get device make and model on iOS?

后端 未结 19 1184
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 04:58

I was wondering if it\'s possible to determine what kind of iPhone (for example) the currentdevice is? I know it\'s possible to get the model through
NSString

19条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 05:04

    If you have a plist of devices (eg maintained by @Tib above in https://stackoverflow.com/a/17655825/849616) to handle it if Swift 3 you'd use:

    extension UIDevice {
        /// Fetches the information about the name of the device.
        ///
        /// - Returns: Should return meaningful device name, if not found will return device system code.
        public static func modelName() -> String {
            let physicalName = deviceSystemCode()
            if let deviceTypes = deviceTypes(), let modelName = deviceTypes[physicalName] as? String {
                return modelName
            }
            return physicalName
        }
    }
    
    private extension UIDevice {
        /// Fetches from system the code of the device
        static func deviceSystemCode() -> String {
            var systemInfo = utsname()
            uname(&systemInfo)
            let machineMirror = Mirror(reflecting: systemInfo.machine)
            let identifier = machineMirror.children.reduce("") { identifier, element in
                guard let value = element.value as? Int8, value != 0 else { return identifier }
                return identifier + String(UnicodeScalar(UInt8(value)))
            }
            return identifier
        }
    
        /// Fetches the plist entries from plist maintained in https://stackoverflow.com/a/17655825/849616
        ///
        /// - Returns: A dictionary with pairs of deviceSystemCode <-> meaningfulDeviceName.
        static func deviceTypes() -> NSDictionary? {
            if let fileUrl = Bundle.main.url(forResource: "your plist name", withExtension: "plist"),
                let configurationDictionary = NSDictionary(contentsOf: fileUrl) {
                return configurationDictionary
            }
            return nil
        }
    }
    

    Later you can call it using UIDevice.modelName().

    Additional credits go to @Tib (for plist), @Aniruddh Joshi (for deviceSystemCode() function).

提交回复
热议问题