Reading osx screenshot image in sandbox

2019-08-11 14:38发布

问题:

I want to get the screenshot triggered by different osx shortcuts. So i add an observer with kMDItemIsScreenCapture. Following code was used to add observer.

_query = [[NSMetadataQuery alloc] init];
[_query setDelegate:self];
[_query setPredicate:[NSPredicate predicateWithFormat:@"kMDItemIsScreenCapture = 1"]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(screenshotQueryUpdated:) name:NSMetadataQueryDidUpdateNotification object:_query];
[_query startQuery];

Implementation of screenshotQueryUpdated is as follow:

NSMetadataItem *item = [[notification.userInfo objectForKey:(NSString *)kMDQueryUpdateAddedItems] lastObject];
if (item) {
    NSString *screenShotPath = [item valueForAttribute:NSMetadataItemPathKey];
    NSData* temp = [NSData dataWithContentsOfFile:screenShotPath];
    // More code....
}

Problem is i can not read file at screenShotPath in sandbox mode. So what is the right way to get screenshot file in application with sandbox.

回答1:

Use an NSOpenPanel to ask the user for access to either this file or the folder containing the screenshots. You will be able to then create a security scoped bookmark to get access on the same resource on subsequent launches of your app.