运行 每 24 小时运行一次 swift 3

Run function every 24hrs swift 3

我得到了一份报价清单,我正尝试根据日历每 24 小时更新一次。

这是我目前尝试的方法,但出现错误 无法将类型 'Date?' 的值转换为预期的参数类型 'TimeInterval'(又名 '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)]
    }
}
let date2: Date  = lastUpdate!

更新:

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

lastUpdate 已经是 Date,初始值设定项 Date(timeIntervalSince1970: 是错误的,无论如何都不需要。

强烈建议使用可选绑定,并且不要注释编译器可以推断的类型。

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