Reputation: 984
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?
Upvotes: 2
Views: 705
Reputation: 1238
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:
let defaults = UserDefaults.standard
struct Bookmark: Codable {
let name: String
let url: String
}
struct Bookmarks: Codable {
let bookmarks: [Bookmark]
}
// data is of type Bookmarks here
if let encodedData = try? JSONEncoder().encode(data) {
defaults.set(encodedData, forKey: "bookmarks")
}
if let savedData = defaults.object(forKey: "bookmarks") as? Data {
if let savedBookmarks = try? JSONDecoder().decode(Bookmarks.self, from: savedData) {
print("Saved user: \(savedBookmarks)")
}
}
Upvotes: 2