Mac电脑如何监听USB设备连接和断开呢?
首先需要区分是监听USB设备还是disk(U盘、SD卡等),如果为后者,则可以直接通过系统通知,而不需要调用IOKit监听,方法如下:
一、监听可装载的USB设备(U盘、SD卡等)
1.注册通知
// Notification for Mountingthe USB device
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(deviceMounted:) name: NSWorkspaceDidMountNotification object: nil];
// Notification for Un-Mountingthe USB device
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(deviceUnmounted:) name: NSWorkspaceDidUnmountNotification object: nil];
2.设备挂载后收到通知
NSArray* devices = [[NSWorkspacesharedWorkspace] mountedRemovableMedia];
3.获取所有已挂载USB的卷路径之后,识别已挂载USB。
#import <IOKit/usb/IOUSBLib.h>
#import <IOKit/IOCFPlugIn.h>
// The following code will return an array having configured Ids and Name of all the mounted USB devices.
-(NSArray *) deviceAttributes {
mach_port_t masterPort;
CFMutableDictionaryRef matchingDict;
NSMutableArray * devicesAttributes = [NSMutableArray array];
kern_return_t kr;
//Create a master port for communication with the I/O Kit
kr = IOMasterPort (MACH_PORT_NULL, &masterPort);
if (kr || !masterPort) {
NSLog (@"Error: Couldn't create a master I/O Kit port(%08x)", kr);
return devicesAttributes;
}
//Set up matching dictionar