0

I have three arrays that i would like to save so they are available when a user exits the app.

I've done research and I know that i should use User Defaults to save these.

Here are the three arrays I would like to save.

var thumbnails = [UIImage]()

var timeArray: [Int] = [Int]()

var videosArray: [URL] = [URL]()

How can I save these three arrays to User Defaults?

John-Philip
  • 3,392
  • 2
  • 23
  • 52
Michael Jajou
  • 312
  • 2
  • 13
  • 2
    UserDefaults is not the proper place to save your app's data, especially large data like images. – rmaddy Jul 23 '17 at 01:53

2 Answers2

1

Don't try to save big objects like images to UserDefaults.

Small arrays of ints or paths are more reasonable.

You can only save a small number of data types into user defaults - "property list objects."

The allowed types are dictionaries, arrays, strings, numbers (integer and float), dates, binary data, and Boolean values.

You should save your images to files on disk, and then save the paths those images to UserDefaults.

Once you have an array of path strings you can save that to UserDefaults directly using the NSArray method write(to:atomically:) or write(toFile:atomically:)

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

UserDefaults allows you to save data using set(,forKey:). If the types aren't allowed in UserDefaults, you could use PropertyListEncoder to archive them correctly.

var urls = [URL]()
let archived = try! PropertyListEncoder().encode(urls) // Data
UserDefaults.standard.set(archived, forKey: "com.app.key1")

You could save those images as files and then save the URLs to each on the device's local storage. Other than that, it's not a good idea to save them as raw NSData/Data. (More info: Persistence of NSURL and file reference URLs)

There's another question in SO with an implementation in objc but it should be simple enough to write it on Swift: Save images in NSUserDefaults?

You should also consider reading about other storage methods using Core Data, Realm, etc.

Edit: Fix major setValue/set issue

nathan
  • 9,329
  • 4
  • 37
  • 51
  • No, do not use `setValue`. That's a key-value coding method, not a direct method of `UserDefaults`. Only use KVC if you have a clear and specific reason to (which is not this case). Also, you can't directly write `UIImage` or `URL` to `UserDefaults`. Please see the documentation for `UserDefaults` for the supported types. – rmaddy Jul 23 '17 at 02:10
  • I added a ref to another question in regards to saving UIImages and also specified that they can be saved as NSData (technically, though not recommended) – nathan Jul 23 '17 at 02:13
  • Again, do not use `setValue`. Please see the documentation for `UserDefaults` for the list of available methods. – rmaddy Jul 23 '17 at 02:25