Thought I’d share this almost-trivial technique for taking screenshots of an iOS device. This will essentially replicate the user pressing the home & power buttons simultaneously, but will return a UIImage for you to use as you please.
Without further ado:
UIViewController+Screenshot.h
#import <Foundation/Foundation.h> @interface UIViewController (Screenshot) - (UIImage *)takeScreenshot; @end
UIViewController+Screenshot.m
#import "UIViewController+Screenshot.h" @implementation UIViewController (Screenshot) - (UIImage *)takeScreenshot { CGRect rect = self.view.bounds; UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); [self.view.layer renderInContext:context]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; } @end
To make use of this, create these two files (or download them here) and add them to your project. Import the UIViewController+Screenshot.h file as needed.
Here’s a quick usage example:
- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; UIImage *screenshot = [self takeScreenshot]; NSString *screenshotPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Screenshots"]; BOOL isDir; __autoreleasing NSError *error; NSFileManager *fm = [NSFileManager defaultManager]; if (!([fm fileExistsAtPath:screenshotPath isDirectory:&isDir] && isDir)) { if (![fm createDirectoryAtPath:screenshotPath withIntermediateDirectories:YES attributes:nil error:&error]) { NSLog(@"Couldn't create screenshot directory. Error: %@", error); return; } } NSDateFormatter *df = [[NSDateFormatter alloc] init]; df.dateFormat = @"yyyyMMddHHmmss"; screenshotPath = [screenshotPath stringByAppendingPathComponent: [NSString stringWithFormat:@"Screenshot_%@.jpg", [UIImageJPEGRepresentation(screenshot, 0.5) writeToFile:screenshotPath atomically:YES]; }
Pretty self-explanatory, I think. Adjust to suit your needs, such as a different path for the images or a different ‘quality’ level for the resultant JPEG file (we’re using 0.5 here).
Hope somebody finds this useful!
UPDATE: NEVER MIND!!!