swift - 在swift中,当应用程序进入后台时,如何使用依赖注入保存变量?
问题描述
我有一个来自 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")
}
}
解决方案
使用 UserDefaults 存储用户,并在需要时从 UserDefaults 中检索它。
但是如果你想在应用程序在后台或者应用程序终止之前存储用户,你必须在 AppDelegate 中实现这两个方法:
func applicationWillTerminate(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
好勇气:)
推荐阅读
- eclipse - jdbc metadata DEBUG RUN 结果差异
- sql - SQL Server 如何使用 information_schema.columns 或 sys.tables 从表列表中进行选择?
- ruby-on-rails - 如何在 S3 访问 ActiveStorage 附件的 URL?
- python - 如何使用 python 将 numpy.ndarray 的人脸编码附加到列表对象中
- c# - WPF - 将故事板放入资源字典
- javascript - 看不懂这个功能
- javascript - 加载视频后的 Vimeo 播放器 enableTextTrack
- sql - 如何将这三个表与 WHERE 子句相关联?
- javascript - Mocha:未捕获的断言错误
- jenkins - 在 jenkins 中创建存档工件的 zip