【问题标题】:SwiftUI - ActionSheet / ShareSheet leads to 'windows' was deprecated in iOS 15.0SwiftUI - ActionSheet / ShareSheet 导致“windows”在 iOS 15.0 中被弃用
【发布时间】:2022-01-14 15:32:24
【问题描述】:

我正在使用通过按钮触发的以下代码在我的应用中显示共享表:

    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)
       }

此代码引发警告:

'windows' 在 iOS 15.0 中已弃用:在相关窗口场景上使用 UIWindowScene.windows 代替

我不明白如何才能摆脱它。已经检查了这里建议的方法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?,但它不起作用。有什么想法可以绕过警告吗?

非常感谢!

【问题讨论】:

    标签: swiftui deprecated deprecation-warning ios-sharesheet


    【解决方案1】:

    您可以使用以下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
            
        }
    }
    

    【讨论】:

    • 谢谢,这可行,但你认为这是预期的方式吗?我猜它只是绕过了错误,但仍然使用苹果的旧方式使用它。建议使用 UIWindowScene.windows,但我不明白它应该如何工作。
    • 不,这是预期的方式 - 如果您仔细观察,它使用 UIWindowScene.windows。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 2021-09-20
    • 2021-11-18
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多