轻按通知后迅速显示警报

所以我要实现的是启动通知并用户点击通知时,出现带有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)
}
ql8568 回答:轻按通知后迅速显示警报

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)
,

尝试一下:

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,completion: nil)

}
,

我认为您是从错误的地方打电话给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()
    }
}
本文链接:https://www.f2er.com/3105485.html

大家都在问