Check out the code to detect all the connected USB.
// main.swift
// USB Demo
//
// Created by Kamala Kannan N G on 04/04/25.
//
import Foundation
class USB {
func detectUSB() {
guard let matchingDict = IOServiceMatching("IOUSBDevice") else {
print("Failed to create matching dictionary")
return
}
var iterator: io_iterator_t = 0
let result = IOServiceGetMatchingServices(kIOMainPortDefault, matchingDict as CFDictionary, &iterator)
guard result == KERN_SUCCESS else {
print("Failed to get matching USB devices. Error: \(result)")
return
}
print("Connected USB devices:")
while case let device = IOIteratorNext(iterator), device != 0 {
defer { IOObjectRelease(device) }
var properties: Unmanaged<CFMutableDictionary>?
if IORegistryEntryCreateCFProperties(device, &properties, kCFAllocatorDefault, 0) == KERN_SUCCESS,
let props = properties?.takeRetainedValue() as? [String: Any] {
let vendor = props["USB Vendor Name"] as? String ?? "Unknown Vendor"
let product = props["USB Product Name"] as? String ?? "Unknown Product"
print("- \(product) by \(vendor)")
}
}
IOObjectRelease(iterator)
}
}
let usb = USB()
usb.detectUSB()
Topic:
Developer Tools & Services
SubTopic:
Xcode
Tags: