Search code examples
swift3nsdateswift4

Run function every 24hrs swift 3


I got a list of quotes I am trying to update every 24hrs, based on the calender.

This is what I tried so far, but I am getting error Cannot convert value of type 'Date?' to expected argument type 'TimeInterval' (aka 'Double')

let numberOfQuotes = 3
let quotes = ["quote 1", "quote 2", "quote 3"]

override func viewDidLoad() {
    super.viewDidLoad()

    let timer = Timer.scheduledTimer(timeInterval: TimeInterval(30),
      target: self, selector: #selector(self.updateQuote), userInfo: nil,  repeats: true)
}

@objc func updateQuote() {
    let lastUpdate = UserDefaults.standard.object(forKey: "lastUpdate") as? Date
    if lastUpdate != nil {
        let date1:Date = Date() // Same you did before with timeNow variable
        let date2: Date = Date(timeIntervalSince1970: lastUpdate ) // **Getting error on this line**

        let calender:Calendar = Calendar.current
        let components: DateComponents = calender.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date1, to: date2)

        if components.day! >= 1 {
            UserDefaults.standard.set(Date(), forKey: "lastUpdate")
         textView.text = "Hello there"
        }

    } else { //firstTime running
        UserDefaults.standard.set(Date(), forKey: "lastUpdate")
        textView.text = quotes[randomInt(min: 0,max: numberOfQuotes)]
    }
}

Solution

  • lastUpdate is already a Date, the initializer Date(timeIntervalSince1970: is wrong and not needed anyway.

    It's highly recommended to use optional bindings, and don't annotate types the compiler can infer.

    if let lastUpdate = UserDefaults.standard.object(forKey: "lastUpdate") as? Date {
        let date1 = Date()
    
        let calender = Calendar.current
        let components = calender.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date1, to: lastUpdate)
    ...