Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
150 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...