2012-09-13 20 views
7

マウントまたはアンマウントされるボリュームに応答する必要があるOS Xアプリケーションがあります。ボリュームがOS Xにマウントされたことを検出する

ボリュームのリストを定期的に取得して変更をチェックすることでこの問題を解決しましたが、より良い方法があるかどうかを知りたいと思います。

答えて

10

登録これらは、ボリューム関連のものです:NSWorkspaceDidRenameVolumeNotificationNSWorkspaceDidMountNotificationNSWorkspaceWillUnmountNotificationNSWorkspaceDidUnmountNotification

2

SCEventsをご存知ですか?監視フォルダの内容が変更されたときに通知されます(/Volumes)。タイマーを使用して内容を定期的にチェックする必要はありません。 。あなたが[[NSWorkspace sharedWorkspace] notificationCenter]から取得し、興味のある通知を処理通知センターに

+0

NSWorkspaceでこれを以下のように使用する理由はありますか?それは第三者図書館なので、プロジェクトに追加の依存関係を追加することを私に納得させるためには、メリットが重要です。 – Brian

15

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"); 
} 
1

スウィフト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) 
    } 
} 

それはここでは、デバイスのパス例えば/ボリューム/ EOS_DIGITAL が印刷されます、あなたがのUserInfoから読み取ることができる定数です。

NSDevicePath, 
NSWorkspaceVolumeLocalizedNameKey 
NSWorkspaceVolumeURLKey 
関連する問題