Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

iOS Swift function isDateInToday not working on some phones

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...