Last active
May 1, 2023 19:10
-
-
Save suzp1984/f14cfab6871e51bee70979a40c1c9760 to your computer and use it in GitHub Desktop.
get display name from NSScreen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension CGDirectDisplayID { | |
func getIOService() -> io_service_t { | |
var serialPortIterator = io_iterator_t() | |
var ioServ: io_service_t = 0 | |
let matching = IOServiceMatching("IODisplayConnect") | |
let kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &serialPortIterator) | |
if KERN_SUCCESS == kernResult && serialPortIterator != 0 { | |
ioServ = IOIteratorNext(serialPortIterator) | |
while ioServ != 0 { | |
let info = IODisplayCreateInfoDictionary(ioServ, UInt32(kIODisplayOnlyPreferredName)).takeRetainedValue() as NSDictionary as! [String: AnyObject] | |
let venderID = info[kDisplayVendorID] as? UInt32 | |
let productID = info[kDisplayProductID] as? UInt32 | |
let serialNumber = info[kDisplaySerialNumber] as? UInt32 ?? 0 | |
if CGDisplayVendorNumber(self) == venderID && | |
CGDisplayModelNumber(self) == productID && | |
CGDisplaySerialNumber(self) == serialNumber { | |
print("found the target io_service_t") | |
break | |
} | |
ioServ = IOIteratorNext(serialPortIterator) | |
} | |
IOObjectRelease(serialPortIterator) | |
} | |
return ioServ | |
} | |
} | |
extension NSScreen { | |
func getDeviceName() -> String? { | |
guard let displayID = | |
deviceDescription[NSDeviceDescriptionKey(rawValue: "NSScreenNumber")] as? CGDirectDisplayID else { | |
print( "can not get CGDirectDisplayID from NSScreen.") | |
return nil | |
} | |
let ioServicePort = displayID.getIOService() | |
if ioServicePort == 0 { | |
print("can not get valide io_service_t.") | |
return nil | |
} | |
guard let info = IODisplayCreateInfoDictionary(ioServicePort, UInt32(kIODisplayOnlyPreferredName)).takeRetainedValue() as? [String: AnyObject] else { | |
print("IODisplayCreateInfoDictionary can not convert to [String: AnyObject]") | |
return nil | |
} | |
if let productName = info["DisplayProductName"] as? [String: String], | |
let firstKey = Array(productName.keys).first { | |
return productName[firstKey]! | |
} | |
return nil | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is my solution, it also works for M1:
https://gist.github.com/AiziChen/6d5e75f36084cb2e2fda84e110375d6b