keyWindow does not always return a UIWindow

ios, keywindow, objective-c, uiview, uiwindow

Solution

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.

Problem

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

Original source