I'm working on an iOS app written in Swift and I want to be able to detect when USB flash drives are connected or disconnected from the device. I'm considering using the External Accessory framework to implement this feature, but I'm not sure where to start. Can anyone provide some guidance or point me to some resources that can help me implement this feature in my app? I'm particularly interested in examples or code snippets that demonstrate how to use the External Accessory framework to detect accessory connection and disconnection events. Any help would be greatly appreciated!
Detecting USB flash drive connection/disconnection events in an iOS app written in Swift
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()