-
Notifications
You must be signed in to change notification settings - Fork 113
/
PListFileStorage.swift
53 lines (46 loc) · 1.41 KB
/
PListFileStorage.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import Foundation
/// Implementation of the FileStorage protocol that reads and writes
/// from and to a plist file at a given URL
///
public final class PListFileStorage: FileStorage {
public init() { }
public func data<T: Decodable>(for fileURL: URL) throws -> T {
do {
let data = try Data(contentsOf: fileURL)
let decoder = PropertyListDecoder()
return try decoder.decode(T.self, from: data)
} catch {
throw PListFileStorageErrors.fileReadFailed
}
}
public func write<T: Encodable>(_ data: T, to fileURL: URL) throws {
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
do {
let encodedData = try encoder.encode(data)
try encodedData.write(to: fileURL)
} catch {
let error = PListFileStorageErrors.fileWriteFailed
throw error
}
}
public func deleteFile(at fileURL: URL) throws {
let fileManager = FileManager.default
guard fileManager.fileExists(atPath: fileURL.path) else {
return
}
do {
try fileManager.removeItem(at: fileURL)
} catch {
let error = PListFileStorageErrors.fileDeleteFailed
throw error
}
}
}
/// Errors
///
enum PListFileStorageErrors: Error {
case fileReadFailed
case fileWriteFailed
case fileDeleteFailed
}