How to check if 3 days have passed

How can I check upload some data every 3 days? All I need to do is check if 3 days or more have passed when the user opens the application, and if so, for the application to download some things? Here is what I have for comparing dates:

var shouldDownload: Bool = false

extension NSDate: Equatable {}
extension NSDate: Comparable {}

public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970
}    

public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
}

extension Int {
    var days: NSTimeInterval {
        let DAY_IN_SECONDS = 60 * 60 * 24
        var days:Double = Double(DAY_IN_SECONDS) * Double(self)
        return days
}
let lastChecked = NSDate()

let interval = NSDate(timeInterval: 3.days, sinceDate: lastChecked)
let today = NSDate()

if interval > today {
    shouldDownload = true
}
+4
source share
2 answers

This is how I do it. Each time your application starts or returns to the forefront, do the following:

  • Read the saved NSDate from NSUserDefaults.

  • Determine the number of midnight elapsed from saved to date. (Do a search in Xcode docs in "Midnights" to find the NSCalendar code to calculate the number of days between two dates.)

  • NSUserDefaults

NSDate:

  /**
  This function calcuates an ordinal day number for the receiver 
  using the Gregorian calendar.

  :returns: an integer day number
  */

  func dayNumber() -> Int
  {
    let calendar = DateUtils.gregorianCalendar
    return calendar.ordinalityOfUnit(NSCalendarUnit.CalendarUnitDay,
      inUnit: NSCalendarUnit.CalendarUnitEra, forDate: self)
  }

DateUtils NSCalendar. , .

class DateUtils
{
  static let gregorianCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
}
+2

:

func isPassedMoreThan(#days: Int, fromDate date : NSDate, toDate date2 : NSDate) -> Bool {
    let deltaDays = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitDay, fromDate: date, toDate: date2, options: nil)
    return deltaDays.day > days
}
+2

All Articles