I cannot figure out how to save data (multiple properties) in Documents Directory with SwiftUI. I know two variants, 1st - when you have one array property and that works great, the problem here - I don't know how to add additional properties to it. Or maybe it is normal to create about 3 swift-files like this for each property for one project.
1 variant, saving in Documents Directory:
class Stack: ObservableObject {
@Published var cards: [Card]
static let saveKey = "SavedCards"
init() {
self.cards = []
if let data = loadFile() {
if let decoded = try? JSONDecoder().decode([Card].self, from: data) {
self.cards = decoded
return
}
}
}
func add(card: Card) {
cards.insert(card, at: 0)
save()
}
func save() {
if let encoded = try? JSONEncoder().encode(cards) {
saveFile(data: encoded)
}
}
private func saveFile(data: Data) {
let url = getDocumentsDirectory().appendingPathComponent(Self.saveKey)
do {
try data.write(to: url, options: [.atomicWrite, .completeFileProtection])
} catch let error {
print("Could not write data: " + error.localizedDescription)
}
}
func loadFile() -> Data? {
let url = getDocumentsDirectory().appendingPathComponent(Self.saveKey)
if let data = try? Data(contentsOf: url) {
return data
}
return nil
}
private func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
}
The 2nd variant is to use CodingKeys for each property. But I cannot figure out how exactly I can add methods here and use it in other views, to save data from pressing a button for example. It seems like I have to encode and decode in every view over and over again for each change of data. It just seems wrong.
2 variant with Coding Keys
class Profile: Codable, ObservableObject {
enum CodingKeys: CodingKey {
case categories, playedCards, playedRounds
}
@Published var categories: [Category] = [Category.red, .green, .blue, .yellow, .pink, .gray]
@Published var playedCards = 0
@Published var playedRounds = 0
init() { }
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
categories = try container.decode([Category].self, forKey: .categories)
playedCards = try container.decode(Int.self, forKey: .playedCards)
playedRounds = try container.decode(Int.self, forKey: .playedRounds)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(categories, forKey: .categories)
try container.encode(playedCards, forKey: .playedCards)
try container.encode(playedRounds, forKey: .playedRounds)
}
}
So my question is how to use 1 variant with multiple variables. Or if I should use the 2nd variant, how can I "nicely" encode and decode variables from other views.
For now, my solution for 2nd variant is to write standard decode() / encode() methods in ContentView and use it in onDismiss: of Sheet Views to save data from different screens without repetitions.
func loadData() {
let filename = getDocumentsDiretory().appendingPathComponent("SavedData")
do {
let data = try Data(contentsOf: filename)
profile = try JSONDecoder().decode(Profile.self, from: data)
} catch {
print("Unable to load saved profile data")
}
}
func saveData() {
do {
let filename = getDocumentsDiretory().appendingPathComponent("SavedData")
let data = try JSONEncoder().encode(self.profile)
try data.write(to: filename, options: [.atomic, .completeFileProtection])
} catch {
print("Unable to save profile data")
}
}
func getDocumentsDiretory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
.sheet(isPresented: $showingSheet, onDismiss: saveData) {
ProfileView()
}
.onAppear(perform: loadData)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.