加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift上的USB连接代理

发布时间:2020-12-14 02:28:47 所属栏目:百科 来源:网络整理
导读:是否有一个 Swift代表可以让我的班级知道何时通过计算机的USB插入新设备?我想知道我的程序何时可以使用新设备. 这个答案对我有用 https://stackoverflow.com/a/35788694但它需要一些改编,比如创建一个桥接头来导入一些特定的IOKit部件. 首先,将IOKit.framew
是否有一个 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设备插入/拔出事件上,它将打印设备名称.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读