Swift上的USB连接代表

Swift上的USB连接代表

本文介绍了Swift上的USB连接代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift中是否有一个委托可以让我的班级知道何时通过计算机的USB插入新设备?我想知道我的程序何时可以使用新设备.

Is there a delegate in Swift that would let my class know when new devices are plugged in via the computer's USB? I would like to know when a new device becomes available to my program.

推荐答案

此答案对我有用 https://stackoverflow.com/a/35788694 ,但需要进行一些修改,例如创建桥接头以导入特定的IOKit部件.

This answer worked for me https://stackoverflow.com/a/35788694 but it needed some adaptation, like creating a bridging header to import some specific IOKit parts.

首先,将IOKit.framework添加到您的项目中(在链接的框架和库"中单击"+").

First, add IOKit.framework to your project (click "+" in "Linked Frameworks and Libraries").

然后创建一个新的空".m"文件,无论其名称如何.然后,Xcode将询问是否应创建桥接标头".说是.

Then create a new empty ".m" file, whatever its name. Xcode will then ask if it should make a "bridging header". Say YES.

忽略".m"文件.在Xcode刚刚创建的新的"YOURAPPNAME-Bridging-Header.h"文件中,添加以下行:

Ignore the ".m" file. In the new "YOURAPPNAME-Bridging-Header.h" file that Xcode just created, add the following lines:

#include <IOKit/IOKitLib.h>
#include <IOKit/usb/IOUSBLib.h>
#include <IOKit/hid/IOHIDKeys.h>

现在,您可以在链接的答案中使用该代码.这是一个简化的版本:

Now you can use the code in the linked answer. Here's a simplified version:

class USBDetector {
    class func monitorUSBEvent() {
        var portIterator: io_iterator_t = 0
        let matchingDict = IOServiceMatching(kIOUSBDeviceClassName)
        let gNotifyPort: IONotificationPortRef = IONotificationPortCreate(kIOMasterPortDefault)
        let runLoopSource: Unmanaged<CFRunLoopSource>! = IONotificationPortGetRunLoopSource(gNotifyPort)
        let gRunLoop: CFRunLoop! = CFRunLoopGetCurrent()
        CFRunLoopAddSource(gRunLoop, runLoopSource.takeRetainedValue(), kCFRunLoopDefaultMode)
        let observer = UnsafeMutablePointer<Void>(unsafeAddressOf(self))
        _ = IOServiceAddMatchingNotification(gNotifyPort,
                                              kIOMatchedNotification,
                                              matchingDict,
                                              deviceAdded,
                                              observer,
                                              &portIterator)
        deviceAdded(nil, iterator: portIterator)
        _ = IOServiceAddMatchingNotification(gNotifyPort,
                                              kIOTerminatedNotification,
                                              matchingDict,
                                              deviceRemoved,
                                              observer,
                                              &portIterator)
        deviceRemoved(nil, iterator: portIterator)
    }
}

func deviceAdded(refCon: UnsafeMutablePointer<Void>, iterator: io_iterator_t) {
    var kr: kern_return_t = KERN_FAILURE
    while case let usbDevice = IOIteratorNext(iterator) where usbDevice != 0 {
        let deviceNameAsCFString = UnsafeMutablePointer<io_name_t>.alloc(1)
        defer {deviceNameAsCFString.dealloc(1)}
        kr = IORegistryEntryGetName(usbDevice, UnsafeMutablePointer(deviceNameAsCFString))
        if kr != KERN_SUCCESS {
            deviceNameAsCFString.memory.0 = 0
        }
        let deviceName = String.fromCString(UnsafePointer(deviceNameAsCFString))
        print("Active device: \(deviceName!)")
        IOObjectRelease(usbDevice)
    }
}

func deviceRemoved(refCon: UnsafeMutablePointer<Void>, iterator: io_iterator_t) {
    // ...
}

注意:deviceAddeddeviceRemoved必须是函数(不是方法).

Note: deviceAdded and deviceRemoved need to be functions (not methods).

要使用此代码,只需启动观察器:

To use this code, just launch the observer:

USBDetector.monitorUSBEvent()

这将列出当前已插入的设备,并且在每个新的USB设备插入/拔出事件中,它将打印设备名称.

This will list the currently plugged devices, and on every new USB device plug/unplug event it will print the device name.

这篇关于Swift上的USB连接代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:44