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

问题描述 投票:2回答:1

以下代码可以很好地获取已连接的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应用程序中运行时才返回任何内容?我错过了什么?

swift hid iokit
1个回答
4
投票

AHA!

在XCode项目中包含一个.entitlements文件,你需要为com.apple.security.device.usb添加一行,并为Cocoa项目设置为“YES”。

© www.soinside.com 2019 - 2024. All rights reserved.