is it possible to detect if a file (e.g. a pdf file opened in preview) was closed?

The FSEvents API does not fire such an event.

Maybe I could observe the associated process or something like that?!

有帮助吗?

解决方案

Yes there is the way that you can find out whether file has been closed or not. So below i tried with unix lsof -t yourFilePath command to determine the same and hence have implemented the same in cocoa. Please follow below here lsof -t yourFilePath will give you the process id of only open files. So that you can easily detect which files are closed:-

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/bash"];
NSString *yourFilePath=@"/Users/Home/Desktop/test.doc";
[task setArguments:[NSArray arrayWithObjects: @"-c",[NSString stringWithFormat:@"%@ %@ %@",@"lsof",@"-t",yourFilePath],nil]];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];
NSString *response = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
if ([response length] > 0)
{
NSLog(@"test.doc file has been opened and process id is %@",response);
}
else
{
NSLog(@"test.doc file has been closed");
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top