5

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?

chaimp
  • 16,897
  • 16
  • 53
  • 86
  • How can I change this to detect usb or serial devices? – Starwave Nov 21 '19 at 22:04
  • Where did you get this code to run perfectly? – Marco Luglio May 30 '20 at 06:04
  • @MarcoLuglio This was from a project that I was working on a couple years ago that can be found here: https://github.com/chaimpeck/CoolerMaster-NumLock-Toggle – chaimp Jun 04 '20 at 16:55
  • see here in particular: https://github.com/chaimpeck/CoolerMaster-NumLock-Toggle/blob/645bf5f14b33e1563b9648a2e5cd82a7b5ec5974/CoolerMasterNumLockToggle/setleds.c#L186 – chaimp Jun 04 '20 at 16:56

2 Answers2

7

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.

chaimp
  • 16,897
  • 16
  • 53
  • 86
  • I just added this but it did not fix things for me. Any idea what could be the problem? I'm on Catalina 10.15.2. Xcode 11.2.1 – Alyoshak Jan 18 '20 at 23:06
1

In projects target, "App Sandbox" section, "Hardware" check "USB":

Menu as described above

Rafael Tavares
  • 5,678
  • 4
  • 32
  • 48
RSQ
  • 11
  • 1