0

I'm making a kind of challenge based app that requires that the user comes back every day. If he misses one day, he has to start all over again. My problem is my dateChanged()-function; the first thing is, that it doesn't work very reliable, the second is that I just check if the date changed, I accordingly don't know if there were one or two days between using the app. Here's my current function:

public func changeDays()
{
    myFormatter.dateStyle = .short
    myFormatter.locale = Locale(identifier: "de_DE")

    oldDate = defaults.string(forKey: "oldDate")!
    let newDate = Date()
    let newDateString = myFormatter.string(from: newDate)

    if newDateString == oldDate
    {
        NumberOfDaysInARow.text = "\(days) / 30"
    }
    else if newDateString != oldDate
    {
        days += 1
        NumberOfDaysInARow.text = "\(days) / 30"
        defaults.set(days, forKey: "days")
    }

    oldDate = newDateString
    defaults.set(oldDate, forKey: "oldDate")


}

Just today it started giving me a fatal error when starting the app on my iPhone, did not happen in the simulator though... weird. How do I have to change my function to make it a 100% reliable (and working) while also being able to check the amount of time between the two dates?

Thank you for having a look! Have a great day

Whazzup
  • 175
  • 2
  • 12

2 Answers2

0

If you look in the documentation you will see that Date has a method whose sole purpose is too determine the interval between two dates time​Interval​Since(_:​).

If you set the old date to always be 11:59PM on the day it was last used you only have to see if the interval is greater than 24 hours worth of seconds (60 seconds * 60 minutes * 24 hours).

You may want to look at the docs for DateComponents for help creating a date that uses the current date but with a specific time.

theMikeSwan
  • 4,739
  • 2
  • 31
  • 44
0

You could extend Date with the function below that returns the amount of days from another date.

extension Date {

  // Returns the amount of days from another date
  func days(from date: Date) -> Int {
    return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
  }
}

Instead of saving oldDate as a string you can set it to defaults as a date:

defaults.set(Date(), forKey: "oldDate")

You can get the old date from defaults using:

let oldDate = defaults.object(forKey:"oldDate") as! Date

Once you have your old date

let dateNow = Date()

let timeDifference = dateNow.days(from: oldDate!)

If timeDifference > 1 {
 // older than 1 day
  } else {
  // Streak still alive 
  }
}
chickenparm
  • 1,570
  • 1
  • 16
  • 36