微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift上的USB连接代理

是否有一个 Swift代表可以让我的班级知道何时通过计算机的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,deviceRemoved,&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设备插入/拔出事件上,它将打印设备名称.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐