Our app requires that the user carries out a daily task. If he/she completes the task, then at midnight a new task is released. If they don't, then come midnight they will continue seeing the previous task until they do.
I'm saving the current date in User Defaults and I'm using isDateInToday to heck if the date has changed:
func checkIfDayChanged() -> Bool {
if let date = UserDefaults.standard.object(forKey: "currentDate") as? Date {
var calendar = Calendar.current
calendar.timeZone = TimeZone.current
let isSameDay = calendar.isDateInToday(date)
if (isSameDay) {
return false
}
}
return true
}
In the majority of cases this works fine. However, there is a small group of users that are stuck with the same task even though they completed it the previous day. For some reason the app is not recognizing that the day is a new one.
Could this be a setting on the phone? Or do I need to change this code? Why wouldn't this be working in only a few devices?
UPDATE:
This is what happens when the daily task (a lesson) is completed:
func onComplete() {
let latestLesson = UserDefaults.standard.integer(forKey: "currentLesson")
if String(latestLesson) == lesson?.lessonNumber {
if (UserDefaults.standard.bool(forKey: "dayLessonCompleted") == false) {
UserDefaults.standard.set(true, forKey: "dayLessonCompleted")
lesson?.completed = true
}
}
}
Every day, the following function runs:
private func checkForMoreLessons() {
// Check the date
let newDay = checkIfDayChanged()
// If the day changed, check if user has watched the previous lesson
if newDay {
if (UserDefaults.standard.bool(forKey: "dayLessonCompleted") == true) {
// Save the new day
UserDefaults.standard.set(Date(), forKey:"currentDate")
// Add 1 to the current date
let currentLesson = UserDefaults.standard.integer(forKey: "currentLesson")
UserDefaults.standard.set(currentLesson + 1, forKey: "currentLesson")
UserDefaults.standard.set(false, forKey: "dayLessonCompleted")
}
}
}
question from:
https://stackoverflow.com/questions/65540722/ios-swift-function-isdateintoday-not-working-on-some-phones 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…