当收到推送通知且应用程序处于打开状态时,我会从AppDelegate显示UIAlertController。问题是,警报不会在第一次运行应用程序时显示。如果您在Xcode中停止应用程序然后重新启动它,一切都按预期工作。
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var alert: UIAlertController?
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
self.showAlert(title: title,message:body,buttonTitle:"View",window:self.window!)
}
func showAlert(title: String,message : String,buttonTitle: String,window: UIWindow){
self.alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert?.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: { (action) in
//self.messageDelegate?.goToMessages()
}))
alert?.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))
window.rootViewController?.present(alert!, animated: false, completion: nil)
}
}