Search code examples
objective-cmacoscocoaosx-mavericksiokit

CGDisplayIOServicePort is deprecated in OS X >= 10.9, how to replace?


I did small app to allow quickly change screen resolutions on multiple monitors. I want to show product name as title of the monitor, and it's very simple to find using this code:

NSDictionary *deviceInfo = (__bridge NSDictionary *)IODisplayCreateInfoDictionary(CGDisplayIOServicePort(dispID), kIODisplayOnlyPreferredName);

NSDictionary *localizedNames = [deviceInfo objectForKey:[NSString stringWithUTF8String:kDisplayProductName]];

if([localizedNames count] > 0) {
    _title = [localizedNames objectForKey:[[localizedNames allKeys] objectAtIndex:0]];
} else {
    _title = @"Unknown display";
}

But CGDisplayIOServicePort is deprecated in OS X >= 10.9 and Apple's documentation says there is no replacement. How to find service port or product name without using this method?

I tried to iterate through IO-registry and tried to use IOServiceGetMatchingServices method to find display services but I'm not very familiar with IO-registry so I couldn't find solution.

Thanks for help!


Solution

  • It looks like @Eun's post missed a piece of information to close this discussion. With a little search, I found that IOServicePortFromCGDisplayID is not an API which Apple provides. Rather, it's a piece of open source code found here: https://github.com/glfw/glfw/blob/e0a6772e5e4c672179fc69a90bcda3369792ed1f/src/cocoa_monitor.m

    I copied IOServicePortFromCGDisplayID and also 'getDisplayName' from it. I needed two tweaks to make it work on OS X 10.10.

    1. Remove the code to handle serial number in IOServicePortFromCGDisplayID. (CFDictionaryGetValue for kDisplaySerialNumber returns NULL for me.)
    2. Remove project specific error handling code in getDisplayName.

    If you need more information

    • Issue tracker of the problem: github.com/glfw/glfw/issues/165
    • Commit for the solution: github.com/glfw/glfw/commit/e0a6772e5e4c672179fc69a90bcda3369792ed1f

    I would thank Matthew Henry who submitted the code there.