J'essaie de présenter un viewcontroller sur topMostViewController. Cela fonctionne dans iOS 12 et inférieur. Mais sur iOS 13, je reçois cette erreur:
L'ajout manuel de la vue rootViewController à la hiérarchie de vues n'est plus pris en charge. Veuillez autoriser UIWindow à ajouter la vue rootViewController à la hiérarchie de vues elle-même.
J'ai vérifié sur iOS 12 et inférieur, et le code ci-dessous fonctionne bien. Mais sur iOS 13, j'ai du mal à présenter le contrôleur de vue. J'ai imprimé sur viewDidLoad
; il s'imprime mais la vue n'apparaît pas.
func presentInWindow(animated flag: Bool = true, completion: (() -> Void)? = nil) {
DispatchQueue.main.async {
var alertWindow: UIWindow?
alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow?.windowLevel = UIWindow.Level.alert + 1
alertWindow?.rootViewController = UIApplication.topViewController()
if let rootViewController = alertWindow?.rootViewController {
alertWindow?.makeKeyAndVisible()
rootViewController.present(self, animated: flag, completion: completion)
}
}
}
static func topViewController() -> UIViewController? {
var topViewController: UIViewController?
if #available(iOS 13.0, *) {
topViewController = shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.map({$0 as? UIWindowScene})
.compactMap({$0})
.first?.windows
.filter({$0.isKeyWindow}).first?.rootViewController
} else {
topViewController = shared.delegate?.window??.rootViewController
}
while true {
if let presented = topViewController?.presentedViewController {
topViewController = presented
} else if let nav = topViewController as? UINavigationController {
topViewController = nav.visibleViewController
} else {
break
}
}
return topViewController
}
J'ai reçu la même erreur lors de la mise à jour d'une application qui fonctionnait bien auparavant. Il semble que la nouvelle exigence pour AppDelegate.Swift soit:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { }
}
hth