-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathGPXFileManager.swift
219 lines (202 loc) · 8.19 KB
/
GPXFileManager.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
//
// GPXFileManager.swift
// OpenGpxTracker
//
// Created by merlos on 20/09/14.
//
import Foundation
///
/// Class to handle actions with GPX files (save, delete, etc..)
///
/// It works on the default document directory of the app.
///
class GPXFileManager: NSObject {
/// List of GPX File extension
static let gpxExtList = ["gpx", "GPX"]
///
/// Folder that where all GPX files are stored
///
class var GPXFilesFolderURL: URL {
if let customFolderURL = Preferences.shared.gpxFilesFolderURL {
print("GPXFileManager: using custom folder: \(customFolderURL)")
return customFolderURL
}
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
return documentsUrl
}
///
/// Gets the list of `.gpx` files in Documents directory ordered by modified date
///
class var fileList: [GPXFileInfo] {
let documentsURL = GPXFileManager.GPXFilesFolderURL
if documentsURL.startAccessingSecurityScopedResource() {
let files = self.fetchFilesList(from: documentsURL)
documentsURL.stopAccessingSecurityScopedResource()
return files
}
return []
}
///
/// Provides the URL in the GPXFilesFolderURL for the filename provided as argument.
///
/// - Parameters:
/// - filename: gpx filename with .gpx extension (f.i: `hola.gpx`) or without extension (f.i: `hola`)
///
class func URLForFilename(_ filename: String) -> URL {
var fullURL = self.GPXFilesFolderURL.appendingPathComponent(filename)
print("URLForFilename(\(filename): pathForFilename: \(fullURL)")
// Check if filename has extension
if !(gpxExtList.contains(fullURL.pathExtension)) {
fullURL = fullURL.appendingPathExtension(gpxExtList[0])
}
return fullURL
}
///
/// Returns true if the file with filename exists on the default folder (GPXFilesFolderURL).
/// False in othercase.
///
/// - Parameters:
/// - filename: Name of the file without extension.
class func fileExists(_ filename: String) -> Bool {
let fileURL = self.URLForFilename(filename)
return FileManager.default.fileExists(atPath: fileURL.path)
}
///
/// Saves the GPX contents to the specified URL
/// - Parameters:
/// - fileURL: destination URL, basically it is file path.
/// - gpxContents: String with the contents to be saved. The XML contents of the GPX file
///
class func saveToURL(_ fileURL: URL, gpxContents: String) {
// Save file
print("Saving file at path: \(fileURL)")
// write gpx to file
var writeError: NSError?
let saved: Bool
do {
try gpxContents.write(toFile: fileURL.path, atomically: true, encoding: String.Encoding.utf8)
saved = true
} catch let error as NSError {
writeError = error
saved = false
}
if !saved {
if let error = writeError {
print("[ERROR] GPXFileManager:save: \(error.localizedDescription)")
}
}
}
///
/// Saves in the default folder the filename with the gpxContents
///
/// - Parameters:
/// - filename: gpx filename with .gpx extension (f.i: `hola.gpx`) or without extension (f.i: `hola`)
/// - gpxContents: String with the contents to be saved. The XML contents of the GPX file
///
class func save(_ filename: String, gpxContents: String) {
// Check if name exists
let fileURL: URL = self.URLForFilename(filename)
GPXFileManager.saveToURL(fileURL, gpxContents: gpxContents)
}
///
/// Moves temporary files received from Apple Watch app to default directory
///
/// - Parameters:
/// - fileURL: URL of temporary file that should be moved/saved.
/// - fileName: name of temporary file, including the file extension (`.gpx`)
///
class func moveFrom(_ fileURL: URL, fileName: String?) {
// check if file name is valid
guard let fileName = fileName else {
print("GPXFileManager:: save failed, error: file name is nil")
return
}
// attempt to move file
do {
let url = GPXFilesFolderURL.path + "/" + fileName
try FileManager().moveItem(atPath: fileURL.path, toPath: url)
}
// file move failure
catch {
print("GPXFileManager:: save failed, error: \(error)")
}
}
/// Removes a file on the specified URL
class func removeFileFromURL(_ fileURL: URL) {
print("Removing file at path: \(fileURL)")
let defaultManager = FileManager.default
var error: NSError?
let deleted: Bool
do {
try defaultManager.removeItem(atPath: fileURL.path)
deleted = true
} catch let error1 as NSError {
error = error1
deleted = false
}
if !deleted {
if let e = error {
print("[ERROR] GPXFileManager:removeFile: \(fileURL) : \(e.localizedDescription)")
}
}
}
///
/// Removes file on the default directory for GPX files
///
/// - Parameters:
/// - filename: gpx filename with .gpx extension (f.i: `hola.gpx`) or without extension (f.i: `hola`)
///
class func removeFile(_ filename: String) {
let fileURL: URL = self.URLForFilename(filename)
GPXFileManager.removeFileFromURL(fileURL)
}
///
/// Removes all files on the application temporary directory (NSTemporaryDirectory())
///
class func removeTemporaryFiles() {
let fileManager = FileManager.default
do {
let tmpDirectory = try fileManager.contentsOfDirectory(atPath: NSTemporaryDirectory())
tmpDirectory.forEach { file in
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(file)
GPXFileManager.removeFileFromURL(fileURL)
}
} catch {
print(error)
}
}
// MARK: - Private
private class func fetchFilesList(from rootURL: URL) -> [GPXFileInfo] {
var GPXFiles: [GPXFileInfo] = []
let fileManager = FileManager.default
print("====================================================================")
do {
// Get all files from the directory .documentsURL. Of each file get the URL (~path)
// last modification date and file size
if let directoryURLs = try? fileManager.contentsOfDirectory(at: rootURL,
includingPropertiesForKeys: [.attributeModificationDateKey, .fileSizeKey],
options: .skipsSubdirectoryDescendants) {
// Order files based on the date
// This map creates a tuple (url: URL, modificationDate: String, filesize: Int)
// and then orders it by modificationDate
let sortedURLs = directoryURLs.map { url in
(url: url,
modificationDate: (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? Date.distantPast,
fileSize: (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize ?? 0)
}
.sorted(by: { $0.1 > $1.1 }) // sort descending modification dates
// Now we filter GPX Files
for (url, modificationDate, fileSize) in sortedURLs {
if gpxExtList.contains(url.pathExtension) {
GPXFiles.append(GPXFileInfo(fileURL: url))
let lastPathComponent = url.deletingPathExtension().lastPathComponent
print("fetchFileList: GPXFileInfo added \(modificationDate) \(modificationDate.timeAgo(numericDates: true)) \(fileSize)bytes -- \(lastPathComponent)")
}
}
}
}
print("fetchFilesList: returned \(GPXFiles.count) files")
print("====================================================================")
return GPXFiles
}
}