swiftmacosnsuserdefaultscore-foundationiphone-privateapi

How to Call a Private macOS CoreFoundation Function from Swift


I'm looking for a way to use a private Apple API from within Swift code (namely, _CFPreferencesCopyApplicationMap, which allows you to look up the paths used for user defaults for any given application).

See this answer for the motivation & the Objective-C solution. I was able to do this in Objective-C with the line:

extern CFDictionaryRef _CFPreferencesCopyApplicationMap(CFStringRef userName, CFStringRef hostName);

I haven't been able to figure out how to do the same in Swift. I know it's possible to dynamically access ObjC objects at runtime using NSClassFromString or NSSelectorFromString, but as far as I can tell these can't be used with global C functions. NSInvocation likewise seems out.


Solution

  • It turns out that this is possible using @_silgen_name:

    @_silgen_name("_CFPreferencesCopyApplicationMap")
    func _CFPreferencesCopyApplicationMap(_: CFString!, _: CFString!) -> CFDictionary!
    
    // Then, call as:
    let applicationMap = _CFPreferencesCopyApplicationMap(kCFPreferencesCurrentUser, kCFPreferencesAnyHost) as? [String: [URL]]