How To Solve “‘windows’ was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead” warning in Swift.

Quick tip on how to fix the error which mostly depends on where you are calling the code in your app.

In my app for example I use a similar code in two places. Common among them is it tries to determine the first key window in the application regardless of the scene.

I have this function that I check from the list of UIApplication.shared.windows and filter by the top .isKeyWindow window so I can retrieve the main rootViewController to navigate to that view in Swift.

static func popToRootView() {
findNavigationController(viewController: UIApplication.shared.windows.filter { $0.isKeyWindow }.first?.rootViewController)?
.popToRootViewController(animated: true)
}
static func findNavigationController(viewController: UIViewController?) -> UINavigationController? {
guard let viewController = viewController else {
return nil
}
if let navigationController = viewController as? UINavigationController {
return navigationController
}
for childViewController in viewController.children {
return findNavigationController(viewController: childViewController)
}
return nil
}

It uses the windows object which has been deprecated in IOS 15.

An improved way is to use UIWindowScene. You first determine the app’s scenes. Then you can traverse the UIWindowScene and grab the controller like so.

static func popToRootView() {
let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
let window = windowScene?.windows.first
findNavigationController(viewController: window?.rootViewController)?
.popToRootViewController(animated: true)
}
static func findNavigationController(viewController: UIViewController?) -> UINavigationController? {
guard let viewController = viewController else {
return nil
}
if let navigationController = viewController as? UINavigationController {
return navigationController
}
for childViewController in viewController.children {
return findNavigationController(viewController: childViewController)
}
return nil
}

This code above works well.

Another code I had to refactor was the one that calls SKStoreViewController to request user reviews.

let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
if let windowScene = windowScene {
SKStoreReviewController.requestReview(in: windowScene)
}

Hope you like this tip, hit the comments below for any questions.

Leave a Reply

Your email address will not be published. Required fields are marked *