Is there a way of getting a Mac's icon given its model number?

前端 未结 3 1430
心在旅途
心在旅途 2020-12-04 01:50

I know you can get the current machine\'s icon from cocoa using the following code:

NSImage *machineIcon = [NSImage imageNamed:NSImageNameComputer];
<         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 02:26

    Here's a solution in Swift, but it uses a private API so remember that it might be subject to undocumented change and App Store rejection.

    struct MachineAttributes {
    
        let privateFrameworksURL = "/System/Library/PrivateFrameworks/ServerInformation.framework/Versions/A/Resources/English.lproj/SIMachineAttributes.plist"
    
        var model: String?
    
        var attributes: [String:AnyObject]?
    
        var iconPath: String?
    
        init() {
            self.model = getModel()
            self.attributes = getAttributes()
            self.iconPath = getIconPath()
        }
    
        init(model: String) {
            self.model = model
            self.attributes = getAttributes()
            self.iconPath = getIconPath()
        }
    
        private func getModel() -> String? {
            let service: io_service_t = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"))
            let cfstr = "model" as CFString
            if let model = IORegistryEntryCreateCFProperty(service, cfstr, kCFAllocatorDefault, 0).takeUnretainedValue() as? NSData {
                if let nsstr = NSString(CString: UnsafePointer(model.bytes), encoding: NSUTF8StringEncoding) {
                    return String(nsstr)
                }
            }
            return nil
        }
    
        private func getAttributes() -> [String:AnyObject]? {
            if let dict = NSDictionary(contentsOfFile: privateFrameworksURL) as? [String:AnyObject],
                let id = model,
                let result = dict[id] as? [String:AnyObject] {
                    return result
            }
            return nil
        }
    
        private func getIconPath() -> String? {
            if let attr = self.attributes, let path = attr["hardwareImageName"] as? String {
                return path
            }
            return nil
        }
    
    }
    

    If you don't know the model:

    let myMachine = MachineAttributes()
    if let model = myMachine.model {
        print(model)
    }
    if let iconPath = myMachine.iconPath {
        print(iconPath)
    }
    

    MacBookPro9,2

    /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/com.apple.macbookpro-15-unibody.icns

    If you know the model or want to use another one:

    let myNamedMachine = MachineAttributes(model: "iMac14,2")
    if let iconPath = myNamedMachine.iconPath {
        print(iconPath)
    }
    

    /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/com.apple.imac-unibody-27-no-optical.icns

提交回复
热议问题