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:
- Init defaults object
let defaults = UserDefaults.standard
- 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]
}
- Save data as follows
// data is of type Bookmarks here
if let encodedData = try? JSONEncoder().encode(data) {
defaults.set(encodedData, forKey: "bookmarks")
}
- 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)")
}
}