Member-only story
Fire Notification if User Doesn’t open app in 24 hours
3 min readOct 9, 2024
Swift function that checks if the app hasn’t been opened in 24 hours and triggers a local notification with an attractive message. This function is independent, so you can call it from anywhere in your app, like inside your ContentView
or any other view
Here’s an updated version of the function that calculates the remaining time until the 24-hour mark and schedules the notification accordingly:
import UserNotifications
func scheduleNotificationIfAppNotOpenedWithin24Hours() {
// Request notification permissions first
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, error in
if let error = error {
print("Error requesting notification permissions: \(error)")
return
}
if granted {
print("Notification permission granted.")
// Proceed with scheduling the notification based on the app's last opened date
let lastOpenedDate = UserDefaults.standard.object(forKey: "lastOpenedDate") as? Date
let currentDate = Date()
// If the app has never been opened, save the current date and exit
if lastOpenedDate == nil {
UserDefaults.standard.set(currentDate, forKey: "lastOpenedDate")
print("First launch, saving the current…