Last active
July 16, 2024 03:06
-
-
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 | |
} | |
} |
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.
#8, kernResult is return 0
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
This solution not worked in M1 machine, any update for M1