![](/img/trans.png)
[英]Is it possible to programmatically change the volume icon on a mounted drive on Mac OS X?
[英]Detect when a volume is mounted on OS X
我有一个OS X应用程序,需要响应已装入或已卸载的卷。
我已经通过定期检索卷列表并检查更改来解决此问题,但是我想知道是否有更好的方法。
NSWorkspace
方法正是我一直在寻找的那种东西。 几行代码之后,我有一个比使用计时器更好的解决方案。
-(void) monitorVolumes
{
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector: @selector(volumesChanged:) name:NSWorkspaceDidMountNotification object: nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector: @selector(volumesChanged:) name:NSWorkspaceDidUnmountNotification object:nil];
}
-(void) volumesChanged: (NSNotification*) notification
{
NSLog(@"dostuff");
}
注册到从[[NSWorkspace sharedWorkspace] notificationCenter]
获得的通知中心,然后处理您感兴趣的通知。这些是与卷相关的通知: NSWorkspaceDidRenameVolumeNotification
, NSWorkspaceDidMountNotification
, NSWorkspaceWillUnmountNotification
和NSWorkspaceDidUnmountNotification
。
你知道SCEvents吗? 当观察到的文件夹的内容更改( /Volumes
)时,它会通知您。 这样,您不必使用计时器来定期检查内容。
Swift 4版本:
在applicationDidFinishLaunching中声明NSWorkspace,并为安装和卸载事件添加观察者。
let workspace = NSWorkspace.shared
workspace.notificationCenter.addObserver(self, selector: #selector(didMount(_:)), name: NSWorkspace.didMountNotification, object: nil)
workspace.notificationCenter.addObserver(self, selector: #selector(didUnMount(_:)), name: NSWorkspace.didUnmountNotification, object: nil)
在以下位置捕获安装和卸载事件:
@objc func didMount(_ notification: NSNotification) {
if let devicePath = notification.userInfo!["NSDevicePath"] as? String {
print(devicePath)
}
}
@objc func didUnMount(_ notification: NSNotification) {
if let devicePath = notification.userInfo!["NSDevicePath"] as? String {
print(devicePath)
}
}
它将打印设备路径,例如/ Volumes / EOS_DIGITAL这是您可以从userInfo读取的常量。
NSDevicePath,
NSWorkspaceVolumeLocalizedNameKey
NSWorkspaceVolumeURLKey
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.