-2

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Bartosz Woźniak
  • 2,065
  • 3
  • 14
  • 31

1 Answers1

1

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • My object is not in Property List (it's not a standard type, like NSDate or NSNumber). How can I add this kind of object to UserDefaults? – Bartosz Woźniak Feb 17 '17 at 18:03
  • Very good question! But that is a question that has been answered many times on Stack Overflow, so just do a search. You can store anything in UserDefaults; you just have to make it archivable into an NSData, and do so. (Might help you to glance at the discussion in my book: http://www.apeth.com/iOSBook/ch36.html#_saving_and_reading_files ) – matt Feb 17 '17 at 18:39
  • @BartoszWoźniak For storing a custom class object in UserDefaults, read something about NSCoding protocol, encode-decode, archive-unarchive http://stackoverflow.com/questions/37980432/swift-3-saving-and-retrieving-custom-object-from-userdefaults – Rajan Maheshwari Feb 17 '17 at 19:44