Search code examples
iosswiftuilocalnotification

Running ios local notification only once after first use


I want to run a local notification one hour after the user stops using the app for the first time. I have set up the following function in a class called LocalNotifications:

static func setupNewUserNotifications() {
    // SCHEDULE NOTIFICATION 1 HOUR AFTER FIRST USE
    
    let content = UNMutableNotificationContent()
    content.title = "Title"
    content.body = "Content."
    content.sound = UNNotificationSound.default

    // show this notification 1 hr from now
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3600, repeats: false) 

    // setup identifier
    let request = UNNotificationRequest(identifier: "NewUser", content: content, trigger: trigger)
    
    // add our notification request
    UNUserNotificationCenter.current().add(request)
}

Then I call this from the AppDelegate:

func applicationWillResignActive(_ application: UIApplication) {

    LocalNotifications.setupNewUserNotifications()

}

The problem is, this triggers the notification every time the user leaves and an hour passes.

How can I get it to run only once?


Solution

  • Set a flag in the UserDefaults, if the flag is true then do not send a notification, otherwise send the notification and write the flag as true.

    static func setupNewUserNotifications() {
    
        let defaults = UserDefaults.standard
    
        // Check for flag, will be false if it has not been set before
        let userHasBeenNotified = defaults.bool(forKey: "userHasBeenNotified")
    
        // Check if the flag is already true, if it's not then proceed
        guard userHasBeenNotified == false else {
            // Flag was true, return from function
            return
        }
    
        // SCHEDULE NOTIFICATION 1 HOUR AFTER FIRST USE
        let content = UNMutableNotificationContent()
        content.title = "Title"
        content.body = "Content."
        content.sound = UNNotificationSound.default
    
        // show this notification 1 hr from now
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3600, repeats: false)
    
        // setup identifier
        let request = UNNotificationRequest(identifier: "NewUser", content: content, trigger: trigger)
    
        // add our notification request
        UNUserNotificationCenter.current().add(request)
    
        // Set the has been notified flag
        defaults.setValue(true, forKey: "userHasBeenNotified")
    }