Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3: Find out, if the date has changed - how?

For my app, I need to find out if the date changed in relation to the last time that you opened the app. For that reason, I made that you can see below. The problem is: it doesn't work for any reason. My app counts the days in a row that you used it so it adds one to a counter of days if the days changed.

Here's my bool:

var dateChanged: Bool
{
    let dateNow = Date()
    var oldDate = defaults.object(forKey: "oldDate2") as? Date

    if dateNow != oldDate
    {
        return true
    }
    else
    {
        return false
    }

    oldDate = newDate
    defaults.set(oldDate, forKey: "oldDate")
    defaults.synchronize()

}

How could I improve that bool? At oldDate = newDate it says: 'Will never be executed.'. Can you help me?

Thank you for having a look!

like image 932
Whazzup Avatar asked Dec 18 '25 21:12

Whazzup


2 Answers

You need to use Calendar method isDateInToday to check date is today's date. Also you need to put the code before returning value from function.

if !Calendar.current.isDateInToday(oldDate) {
    defaults.set(Date(), forKey: "oldDate")
    return true
}
return false
like image 90
Nirav D Avatar answered Dec 20 '25 10:12

Nirav D


In order to know if the date has changed, use UIApplicationSignificantTimeChangeNotification

reference: https://developer.apple.com/documentation/uikit/uiapplication/1623059-significanttimechangenotificatio

like image 21
xGoPox Avatar answered Dec 20 '25 09:12

xGoPox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!