0

我有一个来自 Person 类的变量。我在 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")
        }
    }
4

2 回答 2

0

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

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

    func applicationWillTerminate(_ application: UIApplication) {
        
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        
    }

好勇气:)

于 2020-11-17T09:08:02.180 回答
0

我终于找到了解决方案

我必须在 viewDidLoad 中添加此代码:

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

self.sauvegarderDonneesPersonnne() 是保存人员数据的函数。

于 2020-11-17T09:57:19.313 回答