Skip to content

Instantly share code, notes, and snippets.

@suzp1984
Last active May 1, 2023 19:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suzp1984/f14cfab6871e51bee70979a40c1c9760 to your computer and use it in GitHub Desktop.
Save suzp1984/f14cfab6871e51bee70979a40c1c9760 to your computer and use it in GitHub Desktop.
get display name from NSScreen
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
}
}
@anoopmg
Copy link

anoopmg commented Oct 6, 2021

This solution not worked in M1 machine, any update for M1

@suzp1984
Copy link
Author

which step is failed and return nil (#40, #46, #51, or #59)? Currently, I can't find an M1 machine around me, so I can't debug this issue.

@anoopmg
Copy link

anoopmg commented Oct 21, 2021

#8, kernResult is return 0

@AiziChen
Copy link

AiziChen commented Apr 8, 2022

This is my solution, it also works for M1:
https://gist.github.com/AiziChen/6d5e75f36084cb2e2fda84e110375d6b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment