目前,在iOS 14.6中,我可以使用以下代码在应用程序中调用一个显示共享表的函数:
func share(link: URL) {
let activityView = UIActivityViewController(activityItems: [link], applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(activityView, animated: true, completion: nil)
}
自从iOS 15测试版以来,Xcode告诉我"'windows’在iOS 15.0中被弃用:在相关的窗口场景上使用UIWindowScene.windows。如何更新此信息,以便我的共享工作表在此新版本中正常工作?谢谢
(使用运行在Xcode 13.2.1上的iOS 15.2进行测试(
改进了Rachid的答案,这里有一个Swiftier版本:
extension UIApplication {
var keyWindow: UIWindow? {
// Get connected scenes
return self.connectedScenes
// Keep only active scenes, onscreen and visible to the user
.filter { $0.activationState == .foregroundActive }
// Keep only the first `UIWindowScene`
.first(where: { $0 is UIWindowScene })
// Get its associated windows
.flatMap({ $0 as? UIWindowScene })?.windows
// Finally, keep only the key window
.first(where: .isKeyWindow)
}
}
如果你想在密钥UIWindow
中找到呈现的UIViewController
,这里有另一个你可以找到有用的extension
:
extension UIApplication {
var keyWindowPresentedController: UIViewController? {
var viewController = self.keyWindow?.rootViewController
// If root `UIViewController` is a `UITabBarController`
if let presentedController = viewController as? UITabBarController {
// Move to selected `UIViewController`
viewController = presentedController.selectedViewController
}
// Go deeper to find the last presented `UIViewController`
while let presentedController = viewController?.presentedViewController {
// If root `UIViewController` is a `UITabBarController`
if let presentedController = presentedController as? UITabBarController {
// Move to selected `UIViewController`
viewController = presentedController.selectedViewController
} else {
// Otherwise, go deeper
viewController = presentedController
}
}
return viewController
}
}
你可以把它放在任何你想放的地方,但我个人把它作为extension
添加到UIViewController
。
这允许我添加更多有用的扩展,比如更容易地呈现UIViewController
的扩展,例如:
extension UIViewController {
func presentInKeyWindow(animated: Bool = true, completion: (() -> Void)? = nil) {
DispatchQueue.main.async {
UIApplication.shared.keyWindow?.rootViewController?
.present(self, animated: animated, completion: completion)
}
}
func presentInKeyWindowPresentedController(animated: Bool = true, completion: (() -> Void)? = nil) {
DispatchQueue.main.async {
UIApplication.shared.keyWindowPresentedController?
.present(self, animated: animated, completion: completion)
}
}
}