I am trying to compare two dates, one of them is an older fetched value, if it's smaller then Date() I am storing Date() as the latestConfirmedDate
. If there is no internet connection, the fetched value wouldn't get updates of course.
let latestConfirmedDate = UserDefaults.standard.object(forKey: "latestConfirmedDate") as? Date
if((latestConfirmedDate) != nil)
{
let storedDateInLocalTime = DateFormatter.localizedString(
from: latestConfirmedDate!,
dateStyle: .medium,
timeStyle: .medium)
let currentDateInLocalTime = DateFormatter.localizedString(
from: Date(),
dateStyle: .medium,
timeStyle: .medium)
print(storedDateInLocalTime.description)//Producing the same value each time
print(currentDateInLocalTime.description)
if(Date() > latestConfirmedDate!)
{
UserDefaults.standard.set(Date(),forKey: "latestConfirmedDate")
}
}
In the scenario that there is an internet connection and I am getting a fetched Date object, it stores the fetched value fine in UserDefaults.standard.object(forKey: "latestConfirmedDate")
. But when entering the second If block it doesn't store the current Date().
The weird thing is that the stored value is always staying as the old fetched value, even though I am using UserDefaults.standard.set(Date(),forKey: "latestConfirmedDate")
and the compiler does enters this If block !
17 Nov 2020 at 18:05:58//Stored value, is the old fetched value even though I ran the function a second ago
17 Nov 2020 at 18:29:41//Date()
Where is the problem here ?