Getting Screen as UIImage (XCode) [Solved]

Hi all,

I’m trying to figure out how to get a screenshot (don’t need to save it, just store it in a variable) within xCode (not within Unity).

The img variable just returns a white screen, so I’m thinking the code below isn’t accessing the right view / window.

Does anyone have any ideas how to get the screen as a UIImage within xCode?

        UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
        CGRect rect = [keyWindow bounds];
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [keyWindow.layer renderInContext:context];
        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

Any help would be greatly appreciated.

This code is from an old project so I’m not 100% sure that it will still work, but try:

-(void)doScreenshot
{
    UIScreen *screen = [UIScreen mainScreen] ;
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    UIView *view = [screen snapshotViewAfterScreenUpdates:YES];
    UIGraphicsBeginImageContextWithOptions(screen.bounds.size, NO, 0);
    [keyWindow drawViewHierarchyInRect:keyWindow.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *data= UIImagePNGRepresentation(image);
    [data writeToFile:[NSString stringWithFormat:@"%@/ScreenShot.png",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]] atomically:YES];
}

Awesome that indeed works! Thanks a lot! :smile:

1 Like

That’s great, and no problem!