检测正确的USB设备是否连接 - Swift

发布于 2025-01-26 22:39:54 字数 2071 浏览 3 评论 0原文

使用最新的SwiftUI和Xcode 13,具有OS 12.3+的目标,我需要检测到特定的USB驱动器是否连接到机器。如果是,我需要将变量设置为true,如果将其删除为false。

我还没有找到任何更新的代码示例来执行此操作,而且Apple的文档是... Apple的文档。

我将其与以下代码一起使用,该代码将信息打印到控制台。它仅在指定的volumeUID上寻找USB设备,但是由于它确实是旧的C代码,我希望有人可以共享一种更新的方法,这也可以让我设置一个变量,而不是仅仅打印到安慰。

import DiskArbitration
import Foundation
import IOKit

class USB_Helper: ObservableObject {

    @Published var usbConnected: Bool = false

    init() {
        print("USB Helper Initialized")
        tryUSB()
    }

    func tryUSB() {
        let validation: CFDictionary = [
            "DADeviceProtocol":"USB",
            "DAVolumeUUID": CFUUIDCreateFromString(kCFAllocatorDefault, "F0672BD0-1FA9-3567-452F-322138E12C35" as CFString)!
        ] as CFDictionary

        let diskAppearedCallback: DADiskAppearedCallback = {
            disk,
            context in print(
                "Disk appeared:",
                disk
            )
            printDiskInfo(
                disk
            )
        }

        let diskDisappearedCallback: DADiskDisappearedCallback = {
            disk,
            context in print(
                "Disk disappeared:",
                disk
            )
            printDiskInfo(
                disk
            )
        }

        let runloop = RunLoop.current
        let session = DASessionCreate(kCFAllocatorDefault)!

        func printDiskInfo(_ disk: DADisk) {
            guard let description = DADiskCopyDescription(disk) as? [String: Any] else {
                fatalError()
            }
            print(description)
        }

        DARegisterDiskAppearedCallback(
            session,
            validation,
            diskAppearedCallback,
            nil
        )

        DARegisterDiskDisappearedCallback(
            session,
            validation,
            diskDisappearedCallback,
            nil
        )

        DASessionScheduleWithRunLoop(
            session,
            runloop.getCFRunLoop(),
            CFRunLoopMode.defaultMode.rawValue
        )

    } // End Func

} // End Class

Using the latest SwiftUI and XCode 13, with a target of OS 12.3+ I need to detect whether or not a specific USB drive is connected to the machine. If it is I need to set a variable to true, if it's removed set that var to false.

I have yet to find any sort of updated code examples to do this, and Apple's docs are, well... Apple's docs.

I have it working with the following code, which prints info to the console. It only looks for USB devices with the VolumeUUID specified, but as it's really old C code, I'm hoping someone can share a much more updated way of doing this, which will also allow me to set a variable instead of just printing to the console.

import DiskArbitration
import Foundation
import IOKit

class USB_Helper: ObservableObject {

    @Published var usbConnected: Bool = false

    init() {
        print("USB Helper Initialized")
        tryUSB()
    }

    func tryUSB() {
        let validation: CFDictionary = [
            "DADeviceProtocol":"USB",
            "DAVolumeUUID": CFUUIDCreateFromString(kCFAllocatorDefault, "F0672BD0-1FA9-3567-452F-322138E12C35" as CFString)!
        ] as CFDictionary

        let diskAppearedCallback: DADiskAppearedCallback = {
            disk,
            context in print(
                "Disk appeared:",
                disk
            )
            printDiskInfo(
                disk
            )
        }

        let diskDisappearedCallback: DADiskDisappearedCallback = {
            disk,
            context in print(
                "Disk disappeared:",
                disk
            )
            printDiskInfo(
                disk
            )
        }

        let runloop = RunLoop.current
        let session = DASessionCreate(kCFAllocatorDefault)!

        func printDiskInfo(_ disk: DADisk) {
            guard let description = DADiskCopyDescription(disk) as? [String: Any] else {
                fatalError()
            }
            print(description)
        }

        DARegisterDiskAppearedCallback(
            session,
            validation,
            diskAppearedCallback,
            nil
        )

        DARegisterDiskDisappearedCallback(
            session,
            validation,
            diskDisappearedCallback,
            nil
        )

        DASessionScheduleWithRunLoop(
            session,
            runloop.getCFRunLoop(),
            CFRunLoopMode.defaultMode.rawValue
        )

    } // End Func

} // End Class

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绿光 2025-02-02 22:39:54

答案是,似乎没有办法从回调内设置变量,但是解决方案非常简单。

  1. 您想发送一个
  2. 要捕获该通知的通知,并运行驻留在Tryusb函数之外的函数以设置Bool变量

以下是要设置变量的函数:

@objc func usbTrue() {
    self.usbConnected = true
    print("USB Connected")
}

@objc func usbFalse() {
    self.usbConnected = false
    print("USB Disconnected")
}

以下是通知对回调的修改:

let diskAppearedCallback: DADiskAppearedCallback = {
            disk,
            context in print(
                "Disk appeared:",
                disk
            )
            NotificationCenter.default.post(name: Notification.Name("DiskAppeared"), object: disk)
        }

        NotificationCenter.default.addObserver(self, selector: #selector(usbTrue), name: Notification.Name("DiskAppeared"), object: nil)

        let diskDisappearedCallback: DADiskDisappearedCallback = {
            disk,
            context in print(
                "Disk disappeared:",
                disk
            )
            NotificationCenter.default.post(name: Notification.Name("DiskDisappeared"), object: disk)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(usbFalse), name: Notification.Name("DiskDisappeared"), object: nil)

i真的希望这篇文章对他人有所帮助,因为我花了很长时间才能弄清楚这一点。祝你好运!

The answer is that there seems to be no way to set the variable from within the callback, however the solution is rather simple.

  1. You want to send out a notification
  2. You want to catch that notification and run a function that resides outside of the tryUSB function to set the bool variable

Here are the functions to set the variable:

@objc func usbTrue() {
    self.usbConnected = true
    print("USB Connected")
}

@objc func usbFalse() {
    self.usbConnected = false
    print("USB Disconnected")
}

Here are the modifications to the callbacks with the notifications:

let diskAppearedCallback: DADiskAppearedCallback = {
            disk,
            context in print(
                "Disk appeared:",
                disk
            )
            NotificationCenter.default.post(name: Notification.Name("DiskAppeared"), object: disk)
        }

        NotificationCenter.default.addObserver(self, selector: #selector(usbTrue), name: Notification.Name("DiskAppeared"), object: nil)

        let diskDisappearedCallback: DADiskDisappearedCallback = {
            disk,
            context in print(
                "Disk disappeared:",
                disk
            )
            NotificationCenter.default.post(name: Notification.Name("DiskDisappeared"), object: disk)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(usbFalse), name: Notification.Name("DiskDisappeared"), object: nil)

I really hope this post helps others because it took me a long time to figure it out. Good luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文