-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileSystem.swift
85 lines (76 loc) · 3.21 KB
/
FileSystem.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//
// FileSystem.swift
// Created on 4/10/20.
import Foundation
struct FileSystem {
static private let defaultCacheDataFileName = "objectCache.dat"
static private func getCacheDirectory() -> URL {
let cd = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("com.xyz.cache/", isDirectory: true)
do {
var isDirectory = ObjCBool(true)
if !FileManager.default.fileExists(atPath: cd.path, isDirectory: &isDirectory) {
try FileManager.default.createDirectory(atPath: cd.path, withIntermediateDirectories: true, attributes: nil)
print("Created cache directory: \(cd.path)")
}
} catch {
print(error.localizedDescription)
}
return cd; //this could obviously fail, but we'd simply not be creating cache files properly rather than crash the app
}
static public func writeToCacheDirectory(data: Data, fileName: String = defaultCacheDataFileName) {
let url = self.getCacheDirectory().appendingPathComponent(fileName)
do {
try data.write(to: url, options: .atomic)
print("Wrote to cache file: \(fileName)")
} catch {
print(error.localizedDescription)
}
}
static public func readFromCacheDirectory(fileName: String = defaultCacheDataFileName) -> Data? {
let url = self.getCacheDirectory().appendingPathComponent(fileName)
do {
if FileManager.default.fileExists(atPath: url.path) {
print("Found cache file \(fileName), returning contents.")
return try Data.init(contentsOf: url)
} else {
print("Could not find cache file: \(fileName)")
return nil;
}
} catch {
print(error.localizedDescription)
return nil;
}
}
//honestly this clearcache function is shit - TODO: make it blow out the directory, and test the file array thing.
static public func clearCacheDirectory(fileList:[String]? = nil) {
var filesToDelete:[String] = [];
if (fileList != nil && fileList!.count > 0) {
for file in fileList! {
let filePath = self.getCacheDirectory().appendingPathComponent(file).path
if FileManager.default.fileExists(atPath: filePath)
{
filesToDelete.append(file)
}
}
} else {
do {
filesToDelete = try FileManager.default.contentsOfDirectory(atPath: self.getCacheDirectory().path)
} catch {
print(error.localizedDescription)
}
}
if filesToDelete.isEmpty {
print("FileSystem clearCache: no cache files found to remove!")
} else {
for file in filesToDelete
{
do {
try FileManager.default.removeItem(atPath: self.getCacheDirectory().appendingPathComponent(file).path)
print("Deleted cache file: \(file)")
} catch {
print(error.localizedDescription)
}
}
}
}
}