iosobjective-ccocoa-touchuiapplicationkeywindow

UIApplication sharedApplication keyWindow - iOS App Widget


I have a simple app and widget for iOS 8. I am making use of the UIImage+ImageEffects source files. One of the functions in that library is called "convertViewToImage" which contains the following code:

+ (UIImage *)convertViewToImage
{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [keyWindow bounds];
    UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];
    UIImage *capturedScreen = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return capturedScreen;
}

However, the first line of that method comes us with an error when compiling in an app extension.

UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];

Comes up with the following error:

sharedApplicaion is unavailable: not available on iOS (App Extension) - Use view controller based solutions where appropriate instead.

Does anyone know how I can go about fixing this issue?

Thanks, Dan.


Solution

  • So you cant access the Shared application in an extension. So here are some different ways to achieve what you want.

    try using the snapshotVieAfterScreenUpdates method

    [self.myViewToConvertToImage snapshotViewAfterScreenUpdates:YES];
    

    This returns a UIView that is a snapshot of the complex view.

    alternatively if your after a UIImage to do some processing with

    try

    - (UIImage *)imageFromView:(UIView *)view
    {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
        [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return newImage;
    }