Swift中是否有代表可以通过计算机的USB插入新设备时让我的班级知道?我想知道何时有新设备可供我的程序使用。
这个答案对我有用但是它需要一些修改,例如创建桥接头以导入某些特定的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必须是函数(不是方法)。
deviceAdded
deviceRemoved
要使用此代码,只需启动观察器:
USBDetector.monitorUSBEvent()
这将列出当前已插入的设备,并且在每个新的USB设备插入/拔出事件中,它将打印设备名称。