以下代码可完美获取连接的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应用程序中运行时返回空值?我错过了什么吗?