如何在Swift / Cocoa应用程序中获取HID设备列表?

时间:2018-01-03 02:27:14

标签: swift hid iokit

以下代码可以很好地获取已连接的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内,则devicesnil

如何在Cocoa应用程序中获取设备列表?

为什么IOHIDManagerCopyDevices()只在Cocoa应用程序中运行时才返回任何内容?我错过了什么?

1 个答案:

答案 0 :(得分:4)

AHA!

XCode项目中包含.entitlements个文件,您需要为com.apple.security.device.usb添加一行并将其设置为" YES"对于Cocoa项目。