我下面的快速代码目标是将日期仅存储在时间表中。当用户退出应用程序时。再次运行该应用程序时,标签上应显示的是用户最后一次退出该应用程序的时间。我知道我必须以某种方式将时间表设置为用户第一次离开应用程序时的默认值。我也不知道我对应用程序委托有什么要求。
import UIKit
class ViewController: UIViewController {
var currentDateTime = Date()
var timeLabel = UILabel()
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
view.addSubview(timeLabel)
timeLabel.translatesAutoresizingMaskIntoConstraints = false
timeLabel.backgroundColor = .systemRed
timeLabel.text = "\(dateFormatter.string(from: currentDateTime))"
NSLayoutConstraint.activate([
timeLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 10),
timeLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
timeLabel.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.4, constant: 49),
timeLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.4, constant: 49),
])
defaults.set(timeLabel.text, forKey: "label")
}
}
将侦听器添加到后台回调中并进行设置,您可以在vc内像这样进行操作
NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] notification in
defaults.set(Date(), forKey: "lastDate")
}
或在AppDelegate
方法内部