iOS 应用委托中的弹出消息?

iOS popup message in app delegate?

我尝试在我的应用委托中创建一个弹出式警告消息,但它根本没有显示。程序写的是Swift 4.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let alert = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
    self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}

根据the documentation for didFinishLaunching

Tells the delegate that the launch process is almost done and the app is almost ready to run.

所以我认为您无法在 didFinishLaunchingWithOptions 中显示警报。

尝试将您的代码移动到 applicationDidBecomeActive

如果在 iOS 原生编程中要记住一条规则,那就是:UI 组件只能在主线程上正确操作。记住这一点,我相信它会让你在未来远离头痛。

 let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

    let actionYes = UIAlertAction(title: "Yes", style: .default, handler: { action in
        print("Handler YES")
    })

    let actionCancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { action in
        print("Handler CANCEL")
    })

    alert.addAction(actionYes)
    alert.addAction(actionCancel)

    DispatchQueue.main.async {
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)
    }