我是swift的初学者。
在homeviewController中,我声明了一个标签
@IBOutlet weak var text: UILabel!
如何从安装该应用之日起每周将此数字从0更新为1?
答案 0 :(得分:1)
首先,将启动日期存储在应用首次启动的某个位置,例如NSUserDefaults:NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "installDate")
。然后,只要您需要显示标签,只需找到当前时间与存储时间之间的差异:
let installDate = NSUserDefaults.standardUserDefaults().objectForKey("installDate") as NSDate!
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let unitFlags = NSCalendarUnit.WeekOfYear
let dateComponents = calendar.components(unitFlags, fromDate:installDate, toDate:today, options: NSCalendarOptions.MatchNextTime)
let weeks = dateComponents.weekOfYear
答案 1 :(得分:-1)
使用NSUserDefaults
跟踪您更新text
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "lastUpdate")
然后在方法shouldUpdateTheLabel
中:
func shouldUpdateLabel() {
let lastUpdatedSetting = NSUserDefaults.standardUserDefaults().objectForKey("lastUpdate") as? NSDate
var shouldUpdate = true
if let lastUpdated = lastUpdatedSetting where NSDate().timeIntervalSinceDate(lastUpdated) < 7 * 24 * 60 * 60 {
shouldUpdate = false
}
if shouldUpdate {
text.text = "someTextYouWant"
//Update your label here
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "lastUpdate")
//Record the date you update your label
}else {
return
}
}