寻找每天更新视图的可能性。
这是我尝试过的...但是它甚至不打印“ test2”
var WordNumber = 0
override func viewDidLoad() {
super.viewDidLoad()
let userDefault = UserDefaults.standard
if let lastRe = userDefault.dictionary(forKey: "lastRe") {
print("test2")
if let letztesDatum = lastRe ["date"] as? NSDate {
print("test3")
if let index = lastRe ["index"] as? Int {
print("test4")
if abs(letztesDatum.timeIntervalSinceNow) > 1 {
print("test5")
WordNumber = index + 1
let _ : [NSObject : AnyObject] = ["date" as NSObject : NSDate(),
"index" as NSObject : WordNumber as AnyObject]
}
print("test6")
nextDay() //update lbl
userDefault.set(lastRe, forKey: "lastRe")
userDefault.synchronize()
}
}
}
}
答案 0 :(得分:0)
更简单的解决方案:仅保存日期整数,并添加一个观察者,以便在日期改变时得到通知
override func viewDidLoad() {
super.viewDidLoad()
let today = Calendar.current.component(.day, from: Date())
let lastRe = UserDefaults.standard.integer(forKey: "lastRe")
if today != lastRe {
updateView(day: today)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(forName: .NSCalendarDayChanged, object:nil, queue: .main) { [weak self] _ in
let today = Calendar.current.component(.day, from: Date())
self?.updateView(day: today)
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name:.NSCalendarDayChanged, object:nil)
}
func updateView(day : Int) {
nextDay()
UserDefaults.standard.set(day, forKey: "lastRe")
}
答案 1 :(得分:-1)
if let lastRe = userDefault.dictionary(forKey: "lastRe")
只有找到一个值,以上内容才会执行该块。您没有在UserDefaults中为键lastRe
设置默认值,因此永远不会执行该代码。
尝试设置默认值:
UserDefaults.Standard.set("my initial value here", forKey: "lastRe")