title: Call a function one time per day at a specific time Swift
body: <p>I have a tableview and I want to empty it at a specific time (the user enter in a picker) of the day everyday. Here is the code it mostly work, but lets say the user opened the app at 7pm and the update time is at 8pm the data is not deleted (which is correct) but when the time is at 9pm the same day and the app is opened the data is not deleted (which is incorrect). I think it is something to do with <code>lastRefreshDate</code> being updated evreytime time the app is opened and have to wait for 24hours from <code>lastRefreshDate</code> and not from the <code>userPickedHour</code>. The app should work like this there is a set time 7pm. So the app should delete the data the next day at 7pm or after 7pm when the user open the app but if the user open the app before 7pm the next day it should not delete the data,</p>
  
  <p>Here is the code:</p>
  
  <pre><code>class RefreshManager: NSObject {
  
  static let shared = RefreshManager()
  private let defaults = UserDefaults.standard
  private let defaultsKey = "lastRefresh"
  private let calender = Calendar.current
  
  
  
  func loadDataIfNeeded(completion: (Bool) -&gt; Void) {
  
      if isRefreshRequired() {
          // load the data
          defaults.set(Date(), forKey: defaultsKey)
          print("xxxxxx")
          completion(true)
      } else {
          print("yyyyyy")
          completion(false)
      }
  }
  
  private func isRefreshRequired(userPickedHour: Int = 16) -&gt; Bool {
      let SleepPickerdate = UserDefaults.standard.object(forKey: "SleepDate") as? Date
      let userPickedHour = Calendar.current.component(.hour, from: (SleepPickerdate)!)
      print(userPickedHour)
  
      guard let lastRefreshDate = defaults.object(forKey: defaultsKey) as? Date else {
          return true
      }
  
      if let diff = calender.dateComponents([.hour], from: lastRefreshDate, to: Date()).hour,
          let currentHour =  calender.dateComponents([.hour], from: Date()).hour,
          diff &gt;= 24, userPickedHour &gt;= currentHour {
  
          print("Delete TableView")
          NotificationCenter.default.post(name: NSNotification.Name(rawValue: "Delete"), object: nil)
          print(diff)
          return true
  
      } else {
  
          print("Don't Delete TableView")
  
          return false
  
  
        }
      }
    }
  
  
  
  class ViewController: UIViewController {
  
  let refreshManager = RefreshManager.shared
  
  override func viewDidLoad() {
      super.viewDidLoad()
  
      refreshManager.loadDataIfNeeded() { success in
          print(success)
      }
    }
  }
  </code></pre>