Everyday new content on Application

廉价感情. 提交于 2019-12-13 10:23:08

问题


I have a list of quotes. I want to have a label that changes every 24H to a new Quote. How can I do this? Like how can I manage a day?

I know I could just use an API but I want to use my own quotes and I am not able to create an API on my own yet.


回答1:


Supposing you have an array of quotes:

let numberOfQuotes = 3
let quotes = ["quote a", "quote b", "quote c"]

override func viewDidLoad() {
    _ = Timer.scheduledTimer(timeInterval: TimeInterval(60),
                                               target: self,
                                               selector: #selector(self.updateQuote),
                                               userInfo: nil,
                                               repeats: true)

}

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)

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

       // you can use components month, hour, second.... to update your message, in your case, we will day

       if components.day! >= 1 {
          UserDefaults.standard.set(Date(), forKey: "lastUpdate")
          yourLabel.text = quotes[randomInt(0,numberOfQuotes)]
       }

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

func randomInt(min: Int, max:Int) -> Int {
    return min + Int(arc4random_uniform(UInt32((max - 1) - min + 1)))
}

This code is as is, by your description, it does exactly what you want.



来源:https://stackoverflow.com/questions/45090476/everyday-new-content-on-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!