Is there a delegate in Swift that would let my class know when new devices are plugged in via the computer's USB? I would like to know when a new device becomes available to my program.
相关问题
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
- UIPanGestureRecognizer is not working in iOS 13
- What does a Firebase observer actually do?
相关文章
- 现在使用swift开发ios应用好还是swift?
- Visual Studio Code, MAC OS X, OmniSharp server is
- Using if let syntax in switch statement
- xcode 4 garbage collection removed?
- IntelliJ IDEA can't open projects or add SDK o
- Automator: How do I use the Choose from List actio
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
This answer worked for me https://stackoverflow.com/a/35788694 but it needed some adaptation, like creating a bridging header to import some specific IOKit parts.
First, add IOKit.framework to your project (click "+" in "Linked Frameworks and Libraries").
Then create a new empty ".m" file, whatever its name. Xcode will then ask if it should make a "bridging header". Say YES.
Ignore the ".m" file. In the new "YOURAPPNAME-Bridging-Header.h" file that Xcode just created, add the following lines:
Now you can use the code in the linked answer. Here's a simplified version:
Note:
deviceAdded
anddeviceRemoved
need to be functions (not methods).To use this code, just launch the observer:
This will list the currently plugged devices, and on every new USB device plug/unplug event it will print the device name.
Eric Aya's answer is already quite good, but here's a Swift 3 adaptation. I wrapped most of the ugly stuff in a
USBWatcher
class; set yourself as the delegate of this object to receive notifications.You can copy/paste the following into a playground to see it work — the example just logs a message to the console when devices are connected/disconnected.
It's unfortunate that the IOKit APIs haven't gotten the same Swift-ifying treatment that some other C APIs have been (e.g. CoreGraphics).
io_name_t
is a clunky tuple instead of a proper struct, the way C structs are usually imported to Swift;io_object_t
isn't a real reference type, so it can't take advantage of ARC. Perhaps in the future this will change — if you'd like to see a better Swift API, you should file an enhancement request.