簡體   English   中英

檢測何時在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]獲得的通知中心,然后處理您感興趣的通知。這些是與卷相關的通知: NSWorkspaceDidRenameVolumeNotificationNSWorkspaceDidMountNotificationNSWorkspaceWillUnmountNotificationNSWorkspaceDidUnmountNotification

你知道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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM