I'm trying to execute a function when a local notification is triggered. I have an app that uses local notifications to run a timer, and when the timer finishes I want to save some data to record that the timer has indeed finished. Searching on the internet I was able to write this code:
import SwiftUI
import SwiftData
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
let notificationCenter = UNUserNotificationCenter.current()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// ... other setup code ...
notificationCenter.delegate = self
return true
}
// Handle notification when the app is in the background or terminated
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let identifier = response.notification.request.identifier
if let userInfo = response.notification.request.content.userInfo as? [String: Any] {
if let isTimer = userInfo["isTimer"] as? Bool , isTimer {
let context = Environment(\.modelContext)
let fetchDescriptor = FetchDescriptor<Session>()
do {
let sessions = try context.wrappedValue.fetch(fetchDescriptor)
if let session = sessions.first(where: { $0.id == identifier }) {
session.stopDate = session.startDate.addingTimeInterval(session.timeGoal)
do {
try context.wrappedValue.save()
} catch {
print("Error saving context: \(error)")
}
} else {
print("errore nell'aggiornare la sessione")
}
} catch {
print("Error accessing context: \(error)")
return
}
}
}
completionHandler()
}
}
but it seems that the function isn't called.
Searching some more I found that some people say that this function is called only when the user interacts with the notification, while other people say it's called every time a notification is received.
My question is: if indeed it's called every time a notification is received, why my code doesn't work? And if it's called only when a notification is interacted with, is there a way to do what I need?