我如何在 Spritekit 中显示一个警告框?

How do I present an alertbox in Spritekit?

我不知道如何在 Spritekit 中获得警告框。下面的代码曾经有效,但 KeyWindow 已被弃用,那么我现在该怎么办?

let currentViewController : UIViewController=UIApplication.shared.keyWindow!.rootViewController!

我试过:

let currentViewController : UIViewController = (self.view?.window!.rootViewController)!

任何其他变体,但 none 似乎有效。警报不会弹出。

有人可以解释一下这个问题吗?

完整代码块:

 let ac = UIAlertController(title: "Connect to others", message: nil, preferredStyle: .actionSheet)
 ac.addAction(UIAlertAction(title: "Host a session", style: .default, handler: startHosting))
 ac.addAction(UIAlertAction(title: "Join a session", style: .default, handler: joinSession))
 ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

 let currentViewController :
    UIViewController = (self.view?.window!.rootViewController)!

 currentViewController.present(ac, animated: true, completion: nil)

这行得通,不太确定为什么会这样,但确实行得通。

正在添加 DispatchQueue

DispatchQueue.main.async {
    let ac = UIAlertController(title: "Connect to others", message: nil, preferredStyle: .actionSheet)
        ac.addAction(UIAlertAction(title: "Host a session", style: .default, handler: self.startHosting))
        ac.addAction(UIAlertAction(title: "Join a session", style: .default, handler: self.joinSession))
    ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        self.view?.window?.rootViewController!.present(ac, animated: true, completion: nil)
    }
let alert = UIAlertController(title: "Restore Purchases?", message: "Do you want to restore a purchase?", preferredStyle: .alert)
            let ok = UIAlertAction(title: "OK", style: .default, handler: { action in

                //run code here when ok button is pressed

                 })

            alert.addAction(ok)
            self.view?.window?.rootViewController?.present(alert, animated: true, completion: nil)
}