Iam Wayne
Iam Wayne

Reputation: 561

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)]
    }
}

Upvotes: 2

Views: 603

Answers (2)

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

let date2: Date  = lastUpdate!

UPDATE:

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

Upvotes: 1

vadian
vadian

Reputation: 285069

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)
...

Upvotes: 2

Related Questions