如何在Mac OS X上操作期间防止弹出磁盘?

mcs*_*rey 6 macos objective-c diskarbitration

我有一个长期运行的任务,在已安装的USB驱动器上执行一系列文件操作,我想阻止用户在发生这种情况时从Finder(或其他地方)弹出驱动器.有一个取消按钮,允许任务随时结束.

我曾假设在任务期间保持文件句柄在已安装的卷上打开可以解决问题,但它没有奏效.

这是我尝试的(删除错误处理):

NSString *tempFilePath = @"/Volumes/myVolume/.myTempFile";
if ([[NSFileManager defaultManager] fileExistsAtPath:tempFilePath] == NO) {
    [[NSFileManager defaultManager] createFileAtPath:tempFilePath contents:nil attributes:nil]
}

_tempFile = [NSFileHandle fileHandleForWritingAtPath:tempFilePath];
Run Code Online (Sandbox Code Playgroud)

有关我可以采取哪些措施以确保防止卷弹出的任何想法?

bob*_*vil 10

您需要使用磁盘仲裁 API,更具体地说是DARegisterDiskUnmountApprovalCallback.

您可以DADiskRef通过DADisk.h中的功能创建一个

调用回调后,您可以决定是否要阻止卸载.对于一个人为的例子:

DADissenterRef myUnmountApprovalCallback(DADiskRef disk, void *context)
{
    DADissenterRef result = NULL; // NULL means approval
    if (stillWorking) {
        // This is released by the caller, according to the docs
        result = DADissenterCreate(kCFAllocatorDefault, kDAReturnBusy, CFSTR("<Your App> is busy writing to this device. Please cancel the operation first.");
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

正如评论中所指出的,这不会阻止任何人拔出插头,但它会向您发出明确卸载的通知.