Is there an easy way to store my app's data in Swift 3?
I would like to store a single object in some way. I tried UserDefaults.standard.set(my_object, forKey: "my_object")
but it doesn't seem to work.
I put this code in AppDelegate.swift in func applicationWillTerminate(_ application: UIApplication)
Also, I would like to read this object back in func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
, when the application starts.
UserDefaults is the simplest way.
I put this code in AppDelegate.swift in
func applicationWillTerminate(_ application: UIApplication)
Well, that's pretty silly, because that method is basically never called. Save information out to UserDefaults somewhere such that your code will actually run. applicationDidEnterBackground(_:)
and applicationWillResignActive(_:)
are possible choices, but the way to be certain is simply to save the information out whenever the information changes.
Also, I would like to read this object back in
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
, when the application starts.
Well, 99.9% of the time your application starts, that method won't be called. But if that method is called, fine, go ahead and read the object back in.