在swift中,如何在应用程序进入后台时使用依赖注入保存一个变量?

In swift, how to save a variable with dependency injection, when the app enter background?

我有一个来自 class 人的变量。 我在 AppDelegate 中创建了这个变量,并将它注入到应用程序的任何地方。

我把它转成JSON,为了保存;我在应用程序启动时检索它。 但是当应用程序进入后台时我也需要保存它。 我如何在 SceneDelegate 中检索此变量以保存它?

这是我的 appdelegate

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
        var window: UIWindow?
        var personne = PersonneController()
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        // injection de dépendance : variable personne
        if let AnimationPageDeDemarrageController = window?.rootViewController as? AnimationPageDeDemarrageController {
            AnimationPageDeDemarrageController.personne = self.personne
        }

        // manager le clavier qui cache le texte
        IQKeyboardManager.shared.enable = true
        return true
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        sauvegarderDonneesPersonnne()
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        sauvegarderDonneesPersonnne()
    }
    
    public func sauvegarderDonneesPersonnne() {
        do {
            let appSupport = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            let appSupportDirectory = appSupport.appendingPathComponent(Bundle.main.bundleIdentifier ?? Bundle.main.bundleIdentifier!, isDirectory: true)
            try FileManager.default.createDirectory(at: appSupportDirectory, withIntermediateDirectories: true, attributes: nil)
            let fileURL = appSupportDirectory.appendingPathComponent("Personne.json")
            // encoding
            let data = try personne.shared.data()
            // saving
            try data.write(to: fileURL, options: .atomic)
            print("saved in background")
        } catch {
            print("sauvegarde échouée")
        }
    }

使用 UserDefaults 存储用户,当你需要它时从 UserDefaults 中检索它。

但是如果你想在应用程序在后台或应用程序终止之前存储用户,你必须在 AppDelegate 中实现这两个方法:

    func applicationWillTerminate(_ application: UIApplication) {
        
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        
    }

鼓起勇气:)

我终于找到了解决办法

我必须在 viewDidLoad 中添加这段代码:

NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { (notification) in
            self.sauvegarderDonneesPersonnne()
            //print("app did enter background")
            }

和self.sauvegarderDonneesPersonnne()是保存人物数据的函数