2011-03-17 50 views
2

我想知道是否有方法通过编程方式清空垃圾桶的内容。我目前删除了位于那里使用的文件:通过Objective-C/Cocoa的空垃圾桶

NSFileManager *manager = [NSFileManager defaultManager]; 
    [manager removeItemAtPath:fileToDelete error:nil]; 

但是,我用这个动作后,我每次拖动文件到垃圾箱,我提示消息:

您确定要删除 “xxxxxx.xxx”?该商品将被立即删除 。您无法撤销此操作。

这会持续到我注销或sudo rm -rf垃圾桶。

谢谢!

+0

为什么你需要这样做?垃圾箱是用户的领域,你的应用程序不应该真的搞乱它。 – 2011-03-17 11:15:47

回答

3

你可以把东西放在垃圾桶与NSWorkspace,但是删除垃圾是怎么样的一种没有没有为程序,这样你就不会找到一个API。所以你最好的选择是使用ScriptBridge。

添加ScriptingBridge.framework到您的构建目标,并使用生成的用于取景头文件:

sdef /System/Library/CoreServices/Finder.app/ | sdp -fh --basename Finder 

然后,你可以问搜索,以提示用户清空回收站:

#import "Finder.h" 

FinderApplication *finder = [SBApplication applicationWithBundleIdentifier:@"com.apple.Finder"]; 

// activate finder 
[finder activate]; 

// wait a moment (activate is not instant), then present alert message 
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
    [finder emptySecurity:security]; 
}); 

Scripting Bridge documentation了解更多详情。


作为的Xcode 7.3,如果你试图用这个斯威夫特你会得到链接错误,试图找到Finder.h定义的类。所以你必须创建一个Objective-C包装器。

+0

沙盒怎么样? – 2013-05-08 17:41:00

+0

是的,如果您的应用程序是沙盒,您将需要脚本权利。 – jbtule 2013-05-08 17:58:54

+1

但是,如果您的应用程序是沙盒,那么为什么需要清空垃圾?解决这个问题。 – jbtule 2013-05-08 18:00:15

3

你可以尝试使用AppleScript做到这一点:

NSString* appleScriptString = @"tell application \"Finder\"\n" 
           @"if length of (items in the trash as string) is 0 then return\n" 
           @"empty trash\n" 
           @"repeat until (count items of trash) = 0\n" 
           @"delay 1\n" 
           @"end repeat\n" 
           @"end tell"; 
NSAppleScript* emptyTrashScript = [[NSAppleScript alloc] initWithSource:appleScriptString]; 

[emptyTrashScript executeAndReturnError:nil]; 
[emptyTrashScript release]; 
+0

谢谢!有没有办法一次完成这个文件?我使用回调方法逐个删除文件,并对每个文件执行检查,将其删除,然后转到下一个文件。 – minimalpop 2011-03-17 03:26:11

+0

他们已经在垃圾箱了吗?您无法一次清空垃圾一个文件。但是,您可能可以执行检查,删除文件,然后在完成处理后清空垃圾箱。或者,您可以循环播放垃圾文件中的文件,并将不想删除的文件移出垃圾箱,但这有点适得其反。 – David 2011-03-17 04:15:15