Swift - 儲存資訊、比較日期的應用
需求:當使用者勾選了今天不在顯示某個View,則一直到明天的午夜之前都不顯示該View
應用
- UserDefaults
- Date
- Calendar
UserDefaults 是用來放下次要顯示的時間Double值
取得和設定的基本用法如下(因為在專案中有再包一層,共用、轉型…):
myUserDefaults = NSUserDefaults.standardUserDefaults()
myUserDefaults.setObject( myTextField.text, forKey: "info") myUserDefaults.synchronize()
if let info = myUserDefaults.objectForKey("info") as? String { myLabel.text = info } else { myLabel.text = "尚未儲存資訊" myLabel.textColor = UIColor.redColor() }
取得下次要顯示的日期Double值和判斷如下:
let nextTimeOfConfirmDialog = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date().addingTimeInterval(24*60*60))?.timeIntervalSince1970
UserDefaults.appUserDefault().setDouble(nextTimeOfConfirmDialog!, for: .UserInfoNextShowConfirmDialogTimeIntervalSince1970DoubleKey)
func isTimeToShowConfirmDialog() -> Bool{
let currentDate = Date().timeIntervalSince1970
let timeToShowConfirmDialog = UserDefaults.appUserDefault().getDoubleFor(.UserInfoNextShowConfirmDialogTimeIntervalSince1970DoubleKey)
return currentDate >= timeToShowConfirmDialog
}