0

I have been getting the interface orientation using the following line of code.

let orientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation

However, my new app is targeting iOS 15 and above and I now receive a warning 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead

How do I get rid of this warning and what is the best way to retrieve the device orientation in iOS 15?

Jav Solo
  • 375
  • 1
  • 4
  • 11

2 Answers2

4

You should start with UIApplication.shared.connectedScenes. You probably only have one.

matt
  • 485,702
  • 82
  • 818
  • 1,064
  • Yes, you could also access the same interfaceOrientation using connected scened by first grabbing the UIWindowScene like so `guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return }` however, that is the same UIWindowScene used in my answer below. The answer below gets the active view's window scene and not just the first one though. – Jav Solo Sep 26 '21 at 16:33
  • Well, that's only a concern if you actually have multiple scenes / windows on iPad. I'm betting you probably don't. That's why I say you only have one. – matt Sep 26 '21 at 16:36
  • True, I do not in this particular case. Would my answer give you the current _active_ window if you were on iPadOS? – Jav Solo Sep 26 '21 at 16:37
  • I don't understand the question. If you have only one window you have only one window. – matt Sep 26 '21 at 17:25
  • I would like to know which should be used across iOS and iPadOS safely. In other words, this works in my case, but I would like the accepted answer to be the better replacement to address this deprecation. – Jav Solo Sep 26 '21 at 17:52
  • I'm just telling you what I do. Your answer is limited to situations where `self` is the view controller, which in my view is a very artificial restriction and won't apply to many real-world situations. But you do what you want to do. – matt Sep 26 '21 at 17:59
0

I discovered in another question, that a way around this warning is to instead use the views window and window scene to get the interface orientation like so

let orientation = self.view.window?.windowScene?.interfaceOrientation

The warning goes away now. Thank you to @Marian König's answer

Jav Solo
  • 375
  • 1
  • 4
  • 11
  • 2
    Not only does the warning go away, it is also now correct if for example your app uses airplay to display the view on the second screen. – gnasher729 Sep 25 '21 at 14:58
  • This solution works, however it can be `nil` on application launch before the view is presented and before you may need it to setup some of the views as I discovered. The better way is to do what Matt suggested if that is the case and grab the orientation like so `(UIApplication.shared.connectedScenes.first as! UIWindowScene).interfaceOrientation` – Jav Solo Jan 25 '22 at 23:39