Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of HID devices in a Swift/Cocoa application?

Tags:

swift

hid

iokit

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?

like image 598
chaimp Avatar asked Jan 03 '18 02:01

chaimp


1 Answers

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.

like image 60
chaimp Avatar answered Oct 02 '22 17:10

chaimp