How can I get the last window using UIWindowScene.windows in iOS 15?

3.8k views Asked by At

Going off this post which describes how to get the first window - has definitely helped me learned more about this spec, but it wasn't able to get me the solution I need. How to resolve: 'keyWindow' was deprecated in iOS 13.0

UIApplication.shared.windows.last works like a charm, on iOS 13, 14 and 15. However, it's depreciated in iOS 15 and I am adding an #available statement to make sure it works properly in the future, etc.

Moreover, this is my code and I cannot seem to achieve showing the view I am displaying on top of the UIKeyboard...

    if #available(iOS 15.0, *) {
                
    let scenes = UIApplication.shared.connectedScenes.first as? UIWindowScene
    let window = scenes?.windows.last
                
    if let window = window {
                    
       layer.zPosition = CGFloat(MAXFLOAT)
       frame = window.bounds
       window.addSubview(self)
    }          
 } else {
    if let window = UIApplication.shared.windows.last {
       
       ///
       layer.zPosition = CGFloat(Float.greatestFiniteMagnitude)
       frame = window.bounds
       window.addSubview(self)
     }
  }

To reiterate;

This code works on iOS 13 & iOS 15:

if let window = UIApplication.shared.windows.last {
           
     layer.zPosition = CGFloat(Float.greatestFiniteMagnitude)
     frame = window.bounds
     window.addSubview(self)
  }

This would be fine. However, as of iOS 15, UIApplication.shared.windows has been depreciated. The note in UIApplication.h states: 'Use UIWindowScene.windows on a relevant window scene instead.'

Moreover, this code does NOT work on iOS 15.0:

if #available(iOS 15.0, *) {
            
  let scenes = UIApplication.shared.connectedScenes.first as? UIWindowScene
  let window = scenes?.windows.last
        
  if let window = window {
                
      layer.zPosition = CGFloat(MAXFLOAT)
      frame = window.bounds
      window.addSubview(self)
  }
0

There are 0 answers