我的目标是存储用户退出应用程序时timeLabel
上显示的日期。再次运行应用时,标签的显示时间应与用户退出应用时显示的时间相同。
我知道我必须在用户第一次离开应用程序时以某种方式将timeLabel
保存到用户默认值。我也不知道我是否必须对应用程序委托做任何事情。
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")
}
}
问题是您没有从 UserDefaults 加载字符串。因此,在视图控制器中创建一个方法,以便在应用进入前台时执行,尝试读取字符串并使用它更新标签。
@objc func willEnterForeground(_ notification: Notification) {
if let string = defaults.string(forKey: "label") {
timeLabel.text = string
}
}
要保存用户离开您的应用程序或进入后台的日期,您可以为 iOS12 或更早版本添加观察者 使用UIApplication.willResignActiveNotification
,对于 iOS13 或更高版本,请使用UIScene.willDeactivateNotification
。然后添加一个选择器来处理停用。
对UIScene.willEnterForegroundNotification
和UIApplication.willEnterForegroundNotification
执行相同的操作
将这些观察器添加到viewDidLoad
方法中的视图控制器中:
if #available(iOS 13.0, *) {
NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIScene.willDeactivateNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIScene.willEnterForegroundNotification, object: nil)
} else {
NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
创建将字符串保存到UserDefaults
的方法。目前尚不清楚您的意图是每次用户离开应用程序时保存它,还是只想在第一次保存它。若要在应用每次进入后台时保存它,请执行以下操作:
@objc func willResignActive(_ notification: Notification) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .medium
let string = dateFormatter.string(from: Date())
defaults.set(string, forKey: "label")
}
在后台回调中添加一个侦听器并设置,你可以在 vc 中这样做
NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] notification in
defaults.set(Date(), forKey: "lastDate")
}
或AppDelegate
方法内部