如何在Swift/Cocoa应用程序中获取HID设备列表? [英] How to get list of HID devices in a Swift/Cocoa application?
问题描述
以下代码可以完美地获取已连接的HID设备的列表:
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 :(")
}
如果我使用相同的代码并将其放在applicationDidFinishLaunching
内部的Cocoa应用程序中,则devices
为nil
.
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??
为什么IOHIDManagerCopyDevices()
仅在可可应用程序中运行时不返回任何内容?我想念什么?
Why does IOHIDManagerCopyDevices()
return nothing only when run inside a Cocoa application? What am I missing?
推荐答案
AHA!
XCode项目中包含一个.entitlements
文件,对于Cocoa项目,您需要为com.apple.security.device.usb
添加一行并将其设置为"YES".
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.
这篇关于如何在Swift/Cocoa应用程序中获取HID设备列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!