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

本秂侑毒 提交于 2019-12-14 00:33:14

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/48070396/how-to-get-list-of-hid-devices-in-a-swift-cocoa-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!