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...
//save date?
//if it is same day show me the content picked from "selectedVocab://
//if not the same day rerun code
//my function
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")