当应用程序未收到推送通知时执行代码 运行

Execute code when recieve push notification when app is not running

我正在处理提醒 app.The 应用程序将在特定时间显示通知,这是由 user.I 已使用本地通知显示提醒。

问题是我想在收到本地通知时 运行 一些代码,即使用户没有点击通知。在 swift 中有什么方法可以做到这一点吗?

我认为您应该在 AppDelegate.swift 中添加方法 application(_ application: UIApplication, didReceive notification: UILocalNotification)。您要实现的代码应该在那里。即使用户没有点击通知,代码也会被执行。但无论如何,应用程序应该是 运行。 这是苹果文档的摘录:

If the app is not active in the foreground when the notification fires, the system uses the information in the UILocalNotification object to determine whether it should display an alert, badge the app icon, or play a sound. If the app is running in the foreground, the system calls this method directly without alerting the user in any way.

You might implement this method in your delegate if you want to be notified that a local notification occurred. For example, a calendar app might use local notifications to alert the user to upcoming events.

If the user chooses to open the app when a local notification occurs, the launch options dictionary passed to the application(:willFinishLaunchingWithOptions:) and application(:didFinishLaunchingWithOptions:) methods contains the localNotification key. This method is called at some point after your delegate’s application(_:didFinishLaunchingWithOptions:) method.