以下代码可以很好地获取已连接的HID设备列表:
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 :(")
}
如果我使用相同的代码并将其放在Cocoa应用程序中applicationDidFinishLaunching
内,则devices
为nil
。
如何在Cocoa应用程序中获取设备列表?
为什么IOHIDManagerCopyDevices()
只在Cocoa应用程序中运行时才返回任何内容?我错过了什么?
答案 0 :(得分:4)
AHA!
XCode项目中包含.entitlements
个文件,您需要为com.apple.security.device.usb
添加一行并将其设置为" YES"对于Cocoa项目。