Add images to posts, saving
This commit is contained in:
@ -252,8 +252,28 @@ final class Storage {
|
||||
print("Failed to encode content of \(type) '\(id)': \(error)")
|
||||
return false
|
||||
}
|
||||
return write(data: content, type: type, id: id, to: file)
|
||||
}
|
||||
|
||||
private func write(data: Data, type: String, id: String, to file: URL) -> Bool {
|
||||
if fm.fileExists(atPath: file.path()) {
|
||||
// Check if content is the same, to prevent unnecessary writes
|
||||
do {
|
||||
let oldData = try Data(contentsOf: file)
|
||||
if data == oldData {
|
||||
// File is the same, don't write
|
||||
return true
|
||||
}
|
||||
} catch {
|
||||
print("Failed to read file \(file.path()) for equality check: \(error)")
|
||||
// No check possible, write file
|
||||
}
|
||||
} else {
|
||||
print("Writing new file \(file.path())")
|
||||
}
|
||||
do {
|
||||
try content.write(to: file, options: .atomic)
|
||||
try data.write(to: file, options: .atomic)
|
||||
print("Saved file \(file.path())")
|
||||
return true
|
||||
} catch {
|
||||
print("Failed to save content for \(type) '\(id)': \(error)")
|
||||
@ -272,13 +292,11 @@ final class Storage {
|
||||
}
|
||||
|
||||
private func write(content: String, to file: URL, type: String, id: String) -> Bool {
|
||||
do {
|
||||
try content.write(to: file, atomically: true, encoding: .utf8)
|
||||
return true
|
||||
} catch {
|
||||
print("Failed to save content for \(type) '\(id)': \(error)")
|
||||
guard let data = content.data(using: .utf8) else {
|
||||
print("Failed to convert string to data for \(type) '\(id)'")
|
||||
return false
|
||||
}
|
||||
return write(data: data, type: type, id: id, to: file)
|
||||
}
|
||||
|
||||
private func read<T>(at url: URL) throws -> T where T: Decodable {
|
||||
@ -293,5 +311,4 @@ final class Storage {
|
||||
items[id] = item
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user