以下代码可以完美地获取已连接的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 :(")
}
如果我使用相同的代码并将其放在
applicationDidFinishLaunching
内的Cocoa应用程序中,则devices
是nil
。如何获取 cocoa 应用程序中的设备列表?
为什么
IOHIDManagerCopyDevices()
仅在 cocoa 应用程序中运行时什么也不返回?我想念什么? 最佳答案
啊!
XCode项目中包含一个.entitlements
文件,您需要为com.apple.security.device.usb
添加一行,并为Cocoa项目将其设置为“YES”。
关于swift - 如何在Swift/Cocoa应用程序中获取HID设备列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48070396/