4

I have been using [[UIApplication sharedApplication] keyWindow] to get the visible view of the screen in the form of a UIView. I then convert that view into a UIImage to work with. This is working great except in the case where I show a UIAlertView at the same time. In that case, keyWindow is not returning a UIWindow like it normally does, but instead it is returning a UIModalItemHostingWindow, and after converting that view into an image it's just a pure black screenshot.

Now the docs say keyWindow "holds the UIWindow object in the windows array that is most recently sent the makeKeyAndVisible message."

This UIModalItemHostingWindow must be due to the modal alert I'm presenting, perhaps keyWindow is returning that view instead of the entire screen.

My question is, how can I always guarantee I get a UIView that is an accurate representation of everything visible on screen? It seems keyWindow is not a good solution. One workaround is to delay all of the possible alerts I throw, but I would like to find a better solution if possible

Jordan H
  • 52,571
  • 37
  • 201
  • 351

2 Answers2

4

use [[[UIApplication sharedApplication] delegate] window]

instead of [[UIApplication sharedApplication] keyWindow].

That guarantees you get the UIWindow which is the ultimate root view of the app.

Gon
  • 1,135
  • 12
  • 22
1

Traverse all windows in reverse order (just to make less iterations) and check if window's class is strictly UIWindow:

for (UIWindow *window in [[UIApplication sharedApplication].windows reverseObjectEnumerator]) {
    if ([window class] == [UIWindow class]) {
        // do whatever you want with the window object
        break;
    }
}
kambala
  • 2,341
  • 19
  • 20
  • Thanks for the suggestion! For some reason, there is actually only one window in the windows array when this code is called. – Jordan H Jul 08 '14 at 19:31
  • Even when alert is visible? And is the window of type `UIModalItemHostingWindow`? – kambala Jul 08 '14 at 19:36
  • Yes. Technically `UIModalItemHostingWindow` is a `UIWindow` so when I log `[window class]` it prints `UIWindow`, but in the debugger you can see it's a `UIModalItemHostingWindow` when it should be just `UIWindow` like it is when there is no alert on screen. – Jordan H Jul 08 '14 at 20:13
  • I can work around the issue by delaying the alert presentation. I would like to find a better solution if possible. – Jordan H Jul 15 '14 at 17:42