每隔24小时快速运行一次功能3

时间:2018-02-26 15:44:48

标签: swift3 nsdate swift4

根据日历,我得到了我每24小时更新一次的报价列表。

这是我到目前为止所尝试的内容,但我收到错误无法转换类型'日期的值?'预期参数类型' 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)]
    }
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

let date2: Date  = lastUpdate!

更新:

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