swiftuideprecateddeprecation-warningios-sharesheet

SwiftUI - ActionSheet / ShareSheet leads to 'windows' was deprecated in iOS 15.0


I’m using the following code that gets triggered via a button to display the share sheet in my app:

    func shareSheet() {
           guard let urlShare = URL(string: "https://google.com") else { return }
           let activityVC = UIActivityViewController(activityItems: [urlShare], applicationActivities: nil)
           UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)
       }

This code brings up the warning:

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

I don't understand how I can get rid of it. Already checked the approach suggested here How to get rid of message " 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead" with AdMob banner? but it's not working. Any ideas how I can bypass the warning?

Many Thanks!


Solution

  • You can use following as UIApplication.shared.currentUIWindow()?.rootViewController

    public extension UIApplication {
        func currentUIWindow() -> UIWindow? {
            let connectedScenes = UIApplication.shared.connectedScenes
                .filter({
                    $0.activationState == .foregroundActive})
                .compactMap({$0 as? UIWindowScene})
            
            let window = connectedScenes.first?
                .windows
                .first { $0.isKeyWindow }
    
            return window
            
        }
    }