-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMenuManager.swift
101 lines (86 loc) · 2.97 KB
/
MenuManager.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
import Foundation
func loadLocalDrinks() -> [Drink] { //Load Drink
if let url = Bundle.main.url(forResource: "drinks", withExtension: "json") {
print("File path: \(url.path)")
do {
let data = try Data(contentsOf: url)
let drinks = try JSONDecoder().decode([Drink].self, from: data)
return drinks
} catch {
print("Error decoding JSON: \(error)")
}
} else {
print("File not found.")
}
return []
}
func downloadAndCacheMenu(completion: @escaping ([Drink]?) -> Void) {
// URL of the JSON file on the internet
let urlString = "https://www.grupomovic.com/mixtender/drinks.json"
guard let url = URL(string: urlString) else {
print("Invalid URL")
completion(nil)
return
}
let urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60.0)
let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in
if let error = error {
print("Failed to download data: \(error)")
completion(nil)
return
}
guard let data = data else {
print("No data received")
completion(nil)
return
}
// Save the data to the local cache
saveDataToCache(data: data)
// Decode the JSON data
do {
let drinks = try JSONDecoder().decode([Drink].self, from: data)
completion(drinks)
} catch {
print("Error decoding JSON: \(error)")
completion(nil)
}
}
task.resume()
}
func saveDataToCache(data: Data) {
let fileManager = FileManager.default
guard let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first else {
print("Failed to get cache directory")
return
}
let fileURL = cacheDirectory.appendingPathComponent("drinks.json")
do {
try data.write(to: fileURL)
print("Data saved to cache")
} catch {
print("Failed to save data to cache: \(error)")
}
}
func getDrinksCachedFile() -> [Drink]? {
let fileManager = FileManager.default
guard let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first else {
print("Failed to get cache directory")
return nil
}
let fileURL = cacheDirectory.appendingPathComponent("drinks.json")
if fileManager.fileExists(atPath: fileURL.path) {
print("Cached file found at: \(fileURL.path)")
do {
let data = try Data(contentsOf: fileURL)
// return data
let drinks = try JSONDecoder().decode([Drink].self, from: data)
return drinks
} catch {
print("Failed to read cached file: \(error)")
return nil
}
} else {
print("No cached file found.")
return nil
}
}