Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

ios - Everyday new content on Application

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...