swiftdatensuserdefaults

Comparing two dates in swift in order to check if a day has gone by


In my program, i have a "reset" button that i want to make appear when the user opens the app for the first time each day. So When the view loads, i create a variable to hold what day it is (i.e: 19), and then set that day as a user default. I then use an if statement to determine whether the user default is equal to the actual day it is. I'm not able to get the hiding and unhiding of the "reset" button completely figured out.

Here is the code i have so far. Im new to swift, so any advice or feedback on my approach would be greatly appreciated! Thanks

class UserInfoViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

   let date = Date()
   let calendar = Calendar.current


   let dateToday = calendar.component(.day, from: date)
   let dateToCompare = calendar.component(.day , from: date)

   UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")

   let userDefaultDate = UserDefaults.standard.value(forKey: self.userDefaultDate) as? Int


    if userDefaultDate != dateToCompare {

        resetLabel.isHidden = false
        UserDefaults.standard.set(dateToCompare, forKey: "userDefaultDate")

    }

    if userDefaultDate == dateToCompare {

        resetLabel.isHidden = true
    }
}

Solution

  • Your code cannot work.

    The logic is supposed to be:


    class UserInfoViewController: UIViewController {
    
        override func viewDidLoad() {
           super.viewDidLoad()
    
           let dateToday = Calendar.current.component(.day, from: Date())
           let dateToCompare = UserDefaults.standard.integer(forKey: "userDefaultDate")
           if dateToCompare != dateToCompare {
               UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")
               resetLabel.isHidden = false
            } else {
               resetLabel.isHidden = true
            }
        }
    }
    

    Note:

    Never use value(forKey: with UserDefaults.
    There are many convenience methods and for objects use object(forKey:

    Edit

    It's more reliable to save the Date object and compare using isDateInToday of Calendar

    class UserInfoViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let dateToday = Date()
            let calendar = Calendar.current
            let dateToCompare = UserDefaults.standard.object(forKey: "userDefaultDate") as? Date ?? Date.distantPast
            if calendar.isDateInToday(dateToCompare) {
                resetLabel.isHidden = true
            } else {
                UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")
                resetLabel.isHidden = false
            }
        }
    }