The following code works perfectly to get a list of connected HID devices:
import Foundation
import IOKit
import IOKit.usb
import IOKit.hid
private func createDeviceMatchingDictionary( usagePage: Int, usage: Int) -> CFMutableDictionary {
let dict = [
kIOHIDDeviceUsageKey: usage,
kIOHIDDeviceUsagePageKey: usagePage
] as NSDictionary
return dict.mutableCopy() as! NSMutableDictionary;
}
let manager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone));
let keyboard = createDeviceMatchingDictionary(usagePage: kHIDPage_GenericDesktop, usage: kHIDUsage_GD_Keyboard)
IOHIDManagerOpen(manager, IOOptionBits(kIOHIDOptionsTypeNone) )
IOHIDManagerSetDeviceMatching(manager, keyboard)
let devices = IOHIDManagerCopyDevices(manager)
if (devices != nil) {
print("Found devices!")
}
else {
print("Did not find any devices :(")
}
If I take that same code and put it in a Cocoa application, inside applicationDidFinishLaunching
, then devices
is nil
.
How can I get a list of devices in a Cocoa application??
Why does IOHIDManagerCopyDevices()
return nothing only when run inside a Cocoa application? What am I missing?
AHA!
There is a .entitlements
file included in the XCode project and you need to add a row for com.apple.security.device.usb
and set it to "YES" for a Cocoa project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With