Search code examples
iosiphonescreenshot

How to take a screenshot programmatically on iOS


I want a screenshot of the image on the screen saved into the saved photo library.


Solution

  • I'm answering this question as it's a highly viewed, and there are many answers out there plus there's Swift and Obj-C.

    Disclaimer This is not my code, nor my answers, this is only to help people that land here find a quick answer. There are links to the original answers to give credit where credit is due!! Please honor the original answers with a +1 if you use their answer!


    Using QuartzCore

    #import <QuartzCore/QuartzCore.h> 
    
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
    } else {
        UIGraphicsBeginImageContext(self.window.bounds.size);
    }
    
    [self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *imageData = UIImagePNGRepresentation(image);
    if (imageData) {
        [imageData writeToFile:@"screenshot.png" atomically:YES];
    } else {
        NSLog(@"error while taking screenshot");
    }
    

    In Swift

    func captureScreen() -> UIImage
    {
    
        UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 0);
    
        self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
    
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    
        UIGraphicsEndImageContext()
    
        return image
    }
    

    Note: As the nature with programming, updates may need to be done so please edit or let me know! *Also if I failed to include an answer/method worth including feel free to let me know as well!