【发布时间】:2020-11-17 08:39:56
【问题描述】:
我有一个来自 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")
}
}
【问题讨论】:
-
发布您已经编写的一些代码,以便我们为您提供帮助。你在为 DI 使用 lib 吗?
-
@MickaelBelhassen 我只是在我的问题末尾添加它
-
什么是 PersonneController?请张贴对象
-
@MickaelBelhassen 是这样的:class PersonneController { var shared = Personne() }
标签: swift dependency-injection uiscenedelegate