我有一份报价清单。 我希望有一个标签,每24小时更改一个新的报价。 我怎样才能做到这一点?我怎么能管理一天?
我知道我可以使用API,但我想使用自己的引号,而我自己也无法创建API。
答案 0 :(得分:2)
假设您有一系列引号:
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)))
}
此代码按原样,按照您的描述,它完全符合您的要求。