alschmut / MSALSwiftUI

A SwiftUI representation of the official MSAL UIKit Sample app
MIT License
15 stars 2 forks source link

'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead #1

Open ljunquera opened 2 years ago

ljunquera commented 2 years ago

I am getting this warning in the IDE:

'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead

on this line of code:

let window = UIApplication.shared.windows.filter { $0.isKeyWindow }.first

and when I try:

let window = UIWindowScene.windows.filter { $0.isKeyWindow }.first

I get this error in the IDE:

Instance member 'windows' cannot be used on type 'UIWindowScene'; did you mean to use a value of this type instead?

alschmut commented 2 years ago

@ljunquera Thanks for documenting this issue!

Seems like there is a way to get the top UIViewController from the current scene, using a SceneDelegate, set inside an AppDelegate, which again is injected into the SwiftUI app. To me this doesn't look like the most beautiful solution, but maybe it helps for now.

import SwiftUI
import UIKit

@main
struct AceLifeApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            Text("Hello World!")
        }
    }
}

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        configurationForConnecting connectingSceneSession: UISceneSession,
        options: UIScene.ConnectionOptions
    ) -> UISceneConfiguration {
        let sceneConfig = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)
        sceneConfig.delegateClass = SceneDelegate.self
        return sceneConfig
    }
}

class SceneDelegate: NSObject, UIWindowSceneDelegate {
    let msAuthAdapter: MSAuthAdapterProtocol = resolve()

    func sceneWillEnterForeground(_ scene: UIScene) {
        if
            let delegate = (scene as? UIWindowScene)?.delegate,
            let windowSceneDelegate = delegate as? UIWindowSceneDelegate,
            let topViewController = windowSceneDelegate.window??.rootViewController
        {
            msAuthAdapter.setupViewConnection(with: topViewController)
        }
    }
}