app委托中的iOS弹出消息?

时间:2017-10-30 05:52:35

标签: ios swift appdelegate uialertcontroller

我尝试在我的应用代理中创建一条弹出式提醒消息,但它根本没有显示。该程序是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)
}

2 个答案:

答案 0 :(得分:4)

根据the documentation for didFinishLaunching

  

告诉代表启动过程差不多完成,应用几乎准备好才能运行。

因此,我认为您无法在didFinishLaunchingWithOptions中显示提醒。

尝试将代码移至applicationDidBecomeActive

答案 1 :(得分:-1)

如果在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)
    }