一个简单的方法是使用 NSUserDefaults 来存储一个 NSDictionary,其中包含用户最后一次检索报价的时间和索引。
在 viewDidLoad 中:(或做成独立函数 - checkLastRetrieval())
let userDefaults = NSUserDefaults.standardUserDefaults()
if let lastRetrieval = userDefaults.dictionaryForKey("lastRetrieval") {
if let lastDate = lastRetrieval["date"] as? NSDate {
if let index = lastRetrieval["index"] as? Int {
if abs(lastDate.timeIntervalSinceNow) > 86400 { // seconds in 24 hours
// Time to change the label
var nextIndex = index + 1
// Check to see if next incremented index is out of bounds
if self.myQuoteArray.count <= nextIndex {
// Move index back to zero? Behavior up to you...
nextIndex = 0
}
self.myLabel.text = self.myQuoteArray[nextIndex]
let lastRetrieval : [NSObject : AnyObject] = [
"date" : NSDate(),
"index" : nextIndex
]
userDefaults.setObject(lastRetrieval, forKey: "lastRetrieval")
userDefaults.synchronize()
}
// Do nothing, not enough time has elapsed to change labels
}
}
} else {
// No dictionary found, show first quote
self.myLabel.text = self.myQuoteArray.first!
// Make new dictionary and save to NSUserDefaults
let lastRetrieval : [NSObject : AnyObject] = [
"date" : NSDate(),
"index" : 0
]
userDefaults.setObject(lastRetrieval, forKey: "lastRetrieval")
userDefaults.synchronize()
}
如果您想确保特定时间(如上午 8 点)或确保每个实际日期(周一、周二等)都有唯一的报价,您可以使用 NSDate 更具体。如果用户在 24 小时前看到了报价,则此示例只是更改标签。
查看NSUserDefaults 的文档。
编辑:
如果您想在第二天早上 8 点通知用户新报价,您可以向用户发送local notification。
let notification = UILocalNotification()
notification.fireDate = NSDate(timeIntervalSinceNow: someTimeInterval)
notification.timeZone = NSCalender.currentCalendar().timeZone
notification.alertBody = "Some quote" // or "Check the app"
notiication.hasAction = true
notification.alertAction = "View"
application.scheduleLocalNotification(notification)
您必须将 timeInterval 计算为第二天早上 8 点剩下的任何时间。看看这个答案:https://stackoverflow.com/a/15262058/2881524(这是objective-c,但你应该能够弄清楚)
编辑
要在视图进入前台时执行代码,您需要在 AppDelegate 的 applicationWillEnterForeground 方法中发布通知。并在您的视图控制器中为该通知添加一个观察者。
在AppDelegate
中
let notification = NSNotification(name: "CheckLastQuoteRetrieval", object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)
在ViewController
中
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("checkLastRetrieval"), name: "CheckLastQuoteRetrieval", object: nil)
checkLastRetrieval()
}