退出应用程序时将标签值(日期)存储在 UserDefaults 中

Store label value (date) in UserDefaults on exiting the app

我的目标是在用户退出应用程序时存储 timeLabel 上显示的日期。当应用再次 运行 时,标签显示的时间应与用户退出应用时的时间相同。

我知道我必须在用户第一次离开应用程序时以某种方式将 timeLabel 保存到用户默认值。我也不知道我是否必须对 app delegate 做任何事情。

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 方法内部

问题是您没有从 UserDefaults 加载字符串。因此,在您的视图控制器中创建一个方法,以便在您的应用程序进入前台时执行,尝试读取字符串并使用它更新您的标签。

@objc func willEnterForeground(_ notification: Notification) {
    if let string = defaults.string(forKey: "label") {
        timeLabel.text = string
    }
}

要在用户离开您的应用程序或应用程序进入后台时保存日期,您可以为 iOS12 或更早使用 UIApplication.willResignActiveNotification、iOS13 或更晚添加观察者使用 UIScene.willDeactivateNotification。然后添加一个选择器来处理停用。

UIScene.willEnterForegroundNotificationUIApplication.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")
}