- (void)takeScreenShot {
CGImageRef screenShot = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
CGImageWriteToFile(screenShot, [@"~/code/screenshot.png" stringByExpandingTildeInPath]);
}
BOOL CGImageWriteToFile(CGImageRef image, NSString *path) {
CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);
if (!destination) {
NSLog(@"Failed to create CGImageDestination for %@", path);
return NO;
}
CGImageDestinationAddImage(destination, image, nil);
if (!CGImageDestinationFinalize(destination)) {
NSLog(@"Failed to write image to %@", path);
CFRelease(destination);
return NO;
}
CFRelease(destination);
return YES;
}
Failed to create CGImageDestination for /Users/"username"/Library/Containers/"bundleidentifier"/Data/code/screenshot.png
So no destination is returned. Preferably I would like to write to ~/code/screenshot.png but if it is something with sandboxing it is also ok to write to "sandbox"
How do I write a screenshot to a file that I can access later?
I have adapted code from Saving CGImageRef to a png file?