Swift 中是否有一个委托(delegate)可以让我的类(class)知道何时通过计算机的 USB 插入新设备?我想知道新设备何时可用于我的程序。
最佳答案
这个答案对我有用 https://stackoverflow.com/a/35788694 但它需要一些调整,比如创建一个桥接头来导入一些特定的 IOKit 部件。
首先,将 IOKit.framework 添加到您的项目中(单击“链接的框架和库”中的“+”)。
然后创建一个新的空“.m”文件,不管它的名字是什么。然后 Xcode 会询问它是否应该制作一个“桥接头”。说是。
忽略“.m”文件。在 Xcode 刚刚创建的新“YOURAPPNAME-Bridging-Header.h”文件中,添加以下几行:
#include <IOKit/IOKitLib.h>
#include <IOKit/usb/IOUSBLib.h>
#include <IOKit/hid/IOHIDKeys.h>
现在您可以使用链接答案中的代码。这是一个简化版本:
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) {
// ...
}
注意:
deviceAdded
和 deviceRemoved
需要是函数(不是方法)。要使用此代码,只需启动观察者:
USBDetector.monitorUSBEvent()
这将列出当前插入的设备,并在每个新的 USB 设备插入/拔出事件中打印设备名称。
关于swift - Swift 上的 USB 连接委托(delegate),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39003986/