Ad

Execute Code When Recieve Push Notification When App Is Not Running

I am working on a reminder app.The app will show notifications at particular times which is set by the user.I have used local notifications to show the reminder.

The problem is I want to run some codes when it receives the local notifications even if the user does not tap on the notification. Is there any way to do this in swift ?

Ad

Answer

I believe you should add method application(_ application: UIApplication, didReceive notification: UILocalNotification) inside your AppDelegate.swift. The code you want to be implemented should be there. The code will be executed even the user does not tap on the notification. But anyhow, the app should be running. Here is an extract from apple docs:

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.

Ad
source: stackoverflow.com
Ad