轻按通知后迅速显示警报

时间:2019-11-14 03:49:12

标签: ios swift notifications alert

所以我要实现的是启动通知并用户点击通知时,出现带有2个选项的Alert控制器。但是,从通知水龙头启动应用程序时,什么也没有显示。

这些代码位于AppDelegate.swift文件中

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        showAlert()
}

func showAlert() {
    let alert = UIAlertController(title: "Confirm", message: "Confirm?", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "No", style: .destructive, handler: nil))
    alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: nil))
    window?.rootViewController?.present(alert, animated: true, completion: nil)
}

3 个答案:

答案 0 :(得分:1)

var topVC: UIWindow? = UIWindow(frame: UIScreen.main.bounds)
topVC?.rootViewController = UIViewController()
let alert = UIAlertController(title: "Alert", message: "Notification Received", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel) { _ in
    // action OK
 })
topVC?.makeKeyAndVisible()
topVC?.rootViewController?.present(alert, animated: true, completion: nil)

答案 1 :(得分:0)

尝试一下:

func showAlert() {

var alertController = UIAlertController(title: "Confirm", message: "Confirm?", preferredStyle: UIAlertControllerStyle.alert)
var okAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default) {
                    UIAlertAction in
                    // action
                }
var cancelAction = UIAlertAction(title: "No", style: UIAlertActionStyle.Cancel) {
                    UIAlertAction in
                   // action
                }
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)

}

答案 2 :(得分:0)

我认为您是从错误的地方打电话给func showAlert()。 当应用程序从通知水龙头启动时,该应用程序会在其中获取事件

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool

所以您应该尝试一下

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    //Handle remote notification event on app launch
    if let remoteNotification = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] {
        showAlert()
    }
}