Setting access date in UserDefaults to run a function once a day

Hello there,

Beginner here - I have a function that gives a "word of the day", but I want it to stay in the device for a full 24 hours (regardless of how many times the app is opened or closed) and then rerun the function again the next day to give a new word.

In order to do this I am trying to user UserDefaults, to save the date and to only run the code when it is a new day. I struggling a lot since all the tutorials online are about using UserDefaults to store user preferences.

This is my terrible code so far which makes no sense...

Code Block
 override func viewDidLoad() {
    super.viewDidLoad()

    //save date?
Code Block
 UserDefaults.standard.set(Date(), forKey: "lastAccessDate")
     
let lastAccessDate = UserDefaults.standard.object(forKey: "lastAccessDate") as? Date ?? Date()
     

//if it is same day show me the content picked from "selectedVocab://
Code Block
    if Calendar.current.isDateInToday(lastAccessDate){ 
    userDefaults.value(forKey: "selectedVocab") =
     

//if not the same day rerun code

Code Block
  if !Calendar.current.isDateInToday(lastAccessDate) {
      updateWordOfTheDay()
    }
    }
}

//my function
Code Block
 func updateWordOfTheDay() {
    let selectedVocab = retrieveVocab() // which returns on set of shuffled data
    updateLabels(using: selectedVocab)
    sendNotification(using: selectedVocab)
    //saves to userdefaults?
    userDefaults.setValue(selectedVocab, forKey: "selectedVocab")
     
   

Unfortunately, code has meaning in a certain context and fragments of code, which are in unspecified order, does not make sense.

And, you need to clarify, what is the problem with your current code.
Please show with some amount of all relevant codes.
The current code does not work, so whenever I reopen the app it just gives me a new set of words. This is the only relevant code...

Whenever the user opens the app, it should check if it is the same day. If it is, it should show the word already chosen for that day. If it is a new day it should relaunch updateWordOfTheDay() to show a new word

This is the only relevant code... 

Sorry, but no one can help you with the currently shown code.

Please show full method including method header. Whether your code would work or not depends on which method each line exist in.
Please show full class definition if it is not too long.

Please show all relevant codes if you want some help from other developers.
Not sure I understand how you want to o it and what is your exact spec.

Do you want to notify only when the user has closed the app and reopens, or also when app returns to foreground ?

As OOPer asked, please
  • show the complete code in one file, not a series of separate fragments

  • explain precisely the use case scenario

  • detail what you get as a result and what you expected.

Setting access date in UserDefaults to run a function once a day
 
 
Q