I have a problem getting the current UIScene when multiple scenes are connected.
Specifically, my app (iOS 13) supports multiple windows on the iPad. When I have two windows side by side and I access the apps connected scenes (with UIApplication.shared.connectedScenes), all of them have the activationState set to .foregroundActive. But I am actually only interacting with one of them.
I found some code here on stackoverflow to retrieve the current key window (can't remember who it was that posted it) but as you can see it will always return one of the two windows.
let keyWindow: UIWindow? = UIApplication.shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.map({$0 as? UIWindowScene})
.compactMap({$0})
.first?.windows
.filter({$0.isKeyWindow}).first
Am I missing some method to determine the last window that was interacted with or are the multiple .foregroundActive states a bug?
Thanks!
I found the solution to my problem by refactoring my code so that now I access the current
UIScenes window through thewindowattribute of any view or view controller. This way I don't need thekeyWindowanymore.I think it's probably correct that both windows open next to each other have the
activationState.foregroundActiveIn case anyone needs it, these are the two extensions that helped me get to to current window from anywhere in the app:
But the problem still stands if you don't have access to a
UIView,UIViewControllerorUIScene. For example inside a data model with no reference to a view or scene. Then I don't see a way to consistently accessing the correct window the user is interacting with.