Home > database >  Where to store user data persistently across app updates (iOS)?
Where to store user data persistently across app updates (iOS)?

Time:04-25

I am writing an app that contains a local database. I would like to give the user the possibility to bookmark some items in this database, and that these bookmarks do not disappear every time the app (and thus the database) is updated. What is the best solution in this case?

CodePudding user response:

Simplest method of persisting data across app restarts is by using UserDefaults. In your case you can store custom data types in a UserDefaults key as follows:

  1. Init defaults object
let defaults = UserDefaults.standard
  1. Create a custom data type for your data (needs to be Codable)
struct Bookmark: Codable {
    let name: String
    let url: String
}
struct Bookmarks: Codable {
    let bookmarks: [Bookmark]
}
  1. Save data as follows
// data is of type Bookmarks here
if let encodedData = try? JSONEncoder().encode(data) {
    defaults.set(encodedData, forKey: "bookmarks")
}
  1. Retrieve data later
if let savedData = defaults.object(forKey: "bookmarks") as? Data {
    if let savedBookmarks = try? JSONDecoder().decode(Bookmarks.self, from: savedData) {
        print("Saved user: \(savedBookmarks)")
    }
}

More info here and here

  • Related