Skip to content

Commit 3d3eb22

Browse files
cache data completed (saving money added)
1 parent f397d7f commit 3d3eb22

File tree

5 files changed

+101
-72
lines changed

5 files changed

+101
-72
lines changed

Shared/ContentView.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,12 @@ import Reachability
1414
struct ContentView: View {
1515
let abbreviations = ["BNB", "BTC", "DOGE", "XRP"].sorted()
1616
@State var cryptocurrencies: [Cryptocurrency] = []
17+
@State var unknownErrorAlert: Bool = false
18+
@State var userMoney: Double = 5000
1719

1820
var body: some View {
1921
TabView {
20-
HomeView(abbreviations: abbreviations, cryptocurrencies: $cryptocurrencies)
22+
HomeView(abbreviations: abbreviations, cryptocurrencies: $cryptocurrencies, userMoney: $userMoney, unknownErrorAlert: $unknownErrorAlert)
2123
.tabItem {
2224
Image(systemName: "house")
2325
Text("Home")
@@ -29,7 +31,7 @@ struct ContentView: View {
2931
Text("Exchange Rate")
3032
}
3133

32-
VirtualTradingView(cryptocurrencies: $cryptocurrencies, abbreviations: abbreviations)
34+
VirtualTradingView(cryptocurrencies: $cryptocurrencies, abbreviations: abbreviations, userMoney: $userMoney, unknownErrorAlert: $unknownErrorAlert)
3335
.tabItem {
3436
Image(systemName: "chart.line.uptrend.xyaxis")
3537
Text("Virtual Trading")

Shared/HomeView.swift

Lines changed: 21 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@ struct HomeView: View {
1414
let abbreviations: [String]
1515

1616
@Binding var cryptocurrencies: [Cryptocurrency]
17+
@Binding var userMoney: Double
18+
@Binding var unknownErrorAlert: Bool
1719

18-
@State var unknownErrorAlert: Bool = false
1920
@State var isSyncing: Bool = false
2021
@State var favoriteCryptocurrencies: [Cryptocurrency] = []
2122

@@ -149,7 +150,7 @@ struct HomeView: View {
149150
let button = getStarButton(cryptocurrency: cryptocurrency, imageName: "star.fill") {
150151
removeFromFavoriteCryptocarrencies(cryptocurrency)
151152
cryptocurrency.isFavorite = false
152-
doDummyOnCryptocurrencies()
153+
doDummyOnCryptocurrencies(cryptocurrencies: $cryptocurrencies, userMoney: $userMoney, unknownErrorAlert: $unknownErrorAlert)
153154
}
154155

155156
return BarChartView(data: ChartData(values: data), title: cryptocurrency.name, legend: "Daily", form: ChartForm.medium, cornerButton: button, valueSpecifier: "%.2f")
@@ -222,14 +223,14 @@ struct HomeView: View {
222223
getStarButton(cryptocurrency: cryptocurrency, imageName: "star.fill") {
223224
cryptocurrency.isFavorite = false
224225
removeFromFavoriteCryptocarrencies(cryptocurrency)
225-
doDummyOnCryptocurrencies()
226+
doDummyOnCryptocurrencies(cryptocurrencies: $cryptocurrencies, userMoney: $userMoney, unknownErrorAlert: $unknownErrorAlert)
226227
}
227228
} else {
228229
getStarButton(cryptocurrency: cryptocurrency, imageName: "star") {
229230
cryptocurrency.isFavorite = true
230231
favoriteCryptocurrencies.append(cryptocurrency)
231232
favoriteCryptocurrencies = sortCryptocurrencyByName(favoriteCryptocurrencies)
232-
doDummyOnCryptocurrencies()
233+
doDummyOnCryptocurrencies(cryptocurrencies: $cryptocurrencies, userMoney: $userMoney, unknownErrorAlert: $unknownErrorAlert)
233234
}
234235
}
235236
}
@@ -242,16 +243,6 @@ struct HomeView: View {
242243
.coordinateSpace(name: "")
243244
}
244245

245-
func doDummyOnCryptocurrencies() {
246-
let dummy = Cryptocurrency(symbol: "", name: "", history: [], abbreviation: "")
247-
cryptocurrencies.append(dummy)
248-
cryptocurrencies.removeLast()
249-
250-
for cryptocurrency in cryptocurrencies {
251-
writeData(cryptocurrency)
252-
}
253-
}
254-
255246
func getData() {
256247
isSyncing = true
257248

@@ -282,9 +273,7 @@ struct HomeView: View {
282273
// directory available
283274
try FileManager.default.createDirectory(at: directoryName, withIntermediateDirectories: true)
284275

285-
for abbreviation in abbreviations {
286-
readData(abbreviation)
287-
}
276+
readAllData()
288277
} catch {
289278
// directory unavailable
290279
do {
@@ -297,11 +286,6 @@ struct HomeView: View {
297286
}
298287
}
299288

300-
func getProjectDirectory() -> URL {
301-
let projectDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
302-
return projectDirectory.appendingPathComponent("cryptocurrencies", isDirectory: true)
303-
}
304-
305289
func getCryptocurrencyData(_ abbreviation: String, _ apiKey: String) {
306290
let request = NSMutableURLRequest(url: NSURL(string: "https://api.twelvedata.com/time_series?apikey=\(apiKey)&interval=1day&symbol=\(abbreviation)/USD&dp=2&format=JSON")! as URL,
307291
cachePolicy: .useProtocolCachePolicy,
@@ -347,32 +331,34 @@ struct HomeView: View {
347331
let cryptocurrency = Cryptocurrency(symbol: meta["symbol"]!, name: meta["currency_base"]!, history: history, abbreviation: abbreviation)
348332
cryptocurrencies.append(cryptocurrency)
349333
cryptocurrencies = sortCryptocurrencyByName(cryptocurrencies)
350-
writeData(cryptocurrency)
334+
writeData(cryptocurrency: cryptocurrency, unknownErrorAlert: $unknownErrorAlert)
351335
} else {
352336
cryptocurrency!.history = history
353-
doDummyOnCryptocurrencies()
337+
doDummyOnCryptocurrencies(cryptocurrencies: $cryptocurrencies, userMoney: $userMoney, unknownErrorAlert: $unknownErrorAlert)
354338
}
355339

356340
} else {
357341
runOutOfAPICredits = true
342+
readAllData()
358343
}
359344
} else {
360345
unknownErrorAlert = true
361346
}
362347
}
363348

364-
func writeData(_ cryptocurrency: Cryptocurrency) {
349+
func readAllData() {
350+
let directoryName = getProjectDirectory()
351+
365352
do {
366-
let directoryName = getProjectDirectory()
367-
368-
let jsonEncoder = JSONEncoder()
369-
let jsonData = try jsonEncoder.encode(cryptocurrency)
370-
let json = String(data: jsonData, encoding: .utf8)
371-
let cryptocurrencyDir = directoryName.appendingPathComponent("\(cryptocurrency.abbreviation).txt", isDirectory: true)
372-
try json?.write(to: cryptocurrencyDir, atomically: true, encoding: String.Encoding.utf16)
353+
let moneyDir = directoryName.appendingPathComponent("money.txt", isDirectory: true)
354+
userMoney = Double(try String(contentsOf: moneyDir, encoding: .utf16))!
373355
} catch {
374356
unknownErrorAlert = true
375357
}
358+
359+
for abbreviation in abbreviations {
360+
readData(abbreviation)
361+
}
376362
}
377363

378364
func readData(_ cryptocurrencyAbbreviation: String) {
@@ -392,7 +378,7 @@ struct HomeView: View {
392378
} else {
393379
getCryptocurrency!.history = cryptocurrency.history
394380
getCryptocurrency!.price = cryptocurrency.price
395-
doDummyOnCryptocurrencies()
381+
doDummyOnCryptocurrencies(cryptocurrencies: $cryptocurrencies, userMoney: $userMoney, unknownErrorAlert: $unknownErrorAlert)
396382
}
397383
} catch {
398384
unknownErrorAlert = true
@@ -418,7 +404,7 @@ struct HomeView: View {
418404
} else {
419405
do {
420406
try updatePrice(abbreviation, data!)
421-
doDummyOnCryptocurrencies()
407+
doDummyOnCryptocurrencies(cryptocurrencies: $cryptocurrencies, userMoney: $userMoney, unknownErrorAlert: $unknownErrorAlert)
422408
} catch {
423409
unknownErrorAlert = true
424410
}
@@ -440,6 +426,7 @@ struct HomeView: View {
440426
}
441427
} else {
442428
runOutOfAPICredits = true
429+
readAllData()
443430
}
444431

445432
} else {

Shared/Utils.swift

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,21 @@ func getStarButton(cryptocurrency: Cryptocurrency, imageName: String, action: @e
1515
Button(action: action) {
1616
AnyView(Image(systemName: imageName)
1717
.foregroundColor(Color.yellow)
18-
.font(.system(size: 20, weight: .bold)))
18+
.font(.system(size: 20, weight: .bold)))
1919
}
2020
}
2121

2222
func formatDouble(value: Double) -> String {
2323
var formattedValue = String(format: "%.5f", value)
24-
24+
2525
while formattedValue.last == "0" {
2626
formattedValue.removeLast()
2727
}
28-
28+
2929
if formattedValue.last == "." {
3030
formattedValue.removeLast()
3131
}
32-
32+
3333
return formattedValue
3434
}
3535

@@ -59,3 +59,46 @@ func getDefaultRectangle() -> some View {
5959
.cornerRadius(20)
6060
.shadow(color: Color.gray, radius: 6)
6161
}
62+
63+
func getProjectDirectory() -> URL {
64+
let projectDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
65+
return projectDirectory.appendingPathComponent("cryptocurrencies", isDirectory: true)
66+
}
67+
68+
func doDummyOnCryptocurrencies(cryptocurrencies: Binding<[Cryptocurrency]>, userMoney: Binding<Double>, unknownErrorAlert: Binding<Bool>) {
69+
let dummy = Cryptocurrency(symbol: "", name: "", history: [], abbreviation: "")
70+
cryptocurrencies.wrappedValue.append(dummy)
71+
cryptocurrencies.wrappedValue.removeLast()
72+
73+
writeAllData(cryptocurrencies: cryptocurrencies, userMoney: userMoney, unknownErrorAlert: unknownErrorAlert)
74+
}
75+
76+
func writeAllData(cryptocurrencies: Binding<[Cryptocurrency]>, userMoney: Binding<Double>, unknownErrorAlert: Binding<Bool>) {
77+
let directoryName = getProjectDirectory()
78+
79+
do {
80+
let moneyDir = directoryName.appendingPathComponent("money.txt", isDirectory: true)
81+
try String(userMoney.wrappedValue).write(to: moneyDir, atomically: true, encoding: String.Encoding.utf16)
82+
} catch {
83+
unknownErrorAlert.wrappedValue = true
84+
}
85+
86+
87+
for cryptocurrency in cryptocurrencies.wrappedValue {
88+
writeData(cryptocurrency: cryptocurrency, unknownErrorAlert: unknownErrorAlert)
89+
}
90+
}
91+
92+
func writeData(cryptocurrency: Cryptocurrency, unknownErrorAlert: Binding<Bool>) {
93+
do {
94+
let directoryName = getProjectDirectory()
95+
96+
let jsonEncoder = JSONEncoder()
97+
let jsonData = try jsonEncoder.encode(cryptocurrency)
98+
let json = String(data: jsonData, encoding: .utf8)
99+
let cryptocurrencyDir = directoryName.appendingPathComponent("\(cryptocurrency.abbreviation).txt", isDirectory: true)
100+
try json?.write(to: cryptocurrencyDir, atomically: true, encoding: String.Encoding.utf16)
101+
} catch {
102+
unknownErrorAlert.wrappedValue = true
103+
}
104+
}

Shared/VirtualBuySellView.swift

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import SwiftUI
1010
struct VirtualBuySellView: View {
1111
@State var cryptocurrency: Cryptocurrency
1212
@Binding var userMoney: Double
13+
@Binding var cryptocurrencies: [Cryptocurrency]
14+
@Binding var unknownErrorAlert: Bool
1315

1416
@State private var enoughMoneyAlert = false
1517
@State private var enoughCoinAlert = false
@@ -19,9 +21,11 @@ struct VirtualBuySellView: View {
1921
@State private var dataDidNotLoadAlert = false
2022
@State private var amount = ""
2123

22-
init(_ cryptocurrency: Cryptocurrency, _ userMoney: Binding<Double>) {
24+
init(_ cryptocurrency: Cryptocurrency, _ userMoney: Binding<Double>, cryptocurrencies: Binding<[Cryptocurrency]>, unknownErrorAlert: Binding<Bool>) {
2325
self.cryptocurrency = cryptocurrency
2426
self._userMoney = userMoney
27+
self._cryptocurrencies = cryptocurrencies
28+
self._unknownErrorAlert = unknownErrorAlert
2529
}
2630

2731
func format_double(value: Double) -> String {
@@ -72,6 +76,8 @@ struct VirtualBuySellView: View {
7276
userMoney -= cost
7377
cryptocurrency.virtualTradingAmount += Double(amount)!
7478
buySuccessAlert = true
79+
80+
doDummyOnCryptocurrencies(cryptocurrencies: $cryptocurrencies, userMoney: $userMoney, unknownErrorAlert: $unknownErrorAlert)
7581
}
7682

7783
amount = ""
@@ -110,6 +116,8 @@ struct VirtualBuySellView: View {
110116
userMoney += cost
111117
cryptocurrency.virtualTradingAmount -= Double(amount)!
112118
sellSuccessAlert = true
119+
120+
doDummyOnCryptocurrencies(cryptocurrencies: $cryptocurrencies, userMoney: $userMoney, unknownErrorAlert: $unknownErrorAlert)
113121
}
114122

115123
amount = ""

Shared/VirtualTradingView.swift

Lines changed: 20 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,19 @@ import SwiftUI
99

1010

1111
struct VirtualTradingView: View {
12-
@State var userMoney: Double = 5000
12+
@Binding var userMoney: Double
1313

1414
@Binding var cryptocurrencies: [Cryptocurrency]
15+
@Binding var unknownErrorAlert: Bool
1516
let abbreviations: [String]
1617

1718
@State var dataDidNotLoadAlert: Bool = false
1819

19-
init(cryptocurrencies: Binding<[Cryptocurrency]>, abbreviations: [String]) {
20+
init(cryptocurrencies: Binding<[Cryptocurrency]>, abbreviations: [String], userMoney: Binding<Double>, unknownErrorAlert: Binding<Bool>) {
2021
self._cryptocurrencies = cryptocurrencies
2122
self.abbreviations = abbreviations
23+
self._userMoney = userMoney
24+
self._unknownErrorAlert = unknownErrorAlert
2225
}
2326

2427
func showCoinBar(cryptocurrency: Cryptocurrency) -> some View {
@@ -27,7 +30,7 @@ struct VirtualTradingView: View {
2730
.padding([.leading, .bottom, .trailing])
2831
.overlay(
2932
NavigationLink {
30-
VirtualBuySellView(cryptocurrency, $userMoney)
33+
VirtualBuySellView(cryptocurrency, $userMoney, cryptocurrencies: $cryptocurrencies, unknownErrorAlert: $unknownErrorAlert)
3134
} label: {
3235
HStack {
3336
getLeftSideOfRectangle(cryptocurrency: cryptocurrency, vSpacing: vSpacing)
@@ -53,27 +56,6 @@ struct VirtualTradingView: View {
5356

5457
}
5558
)
56-
// return HStack {
57-
// Image(cryptocurrency.name)
58-
// .resizable()
59-
// .scaledToFit()
60-
// .frame(width: 70, height: 70)
61-
// .padding(.trailing)
62-
// VStack {
63-
// NavigationLink {
64-
// VirtualBuySellView(cryptocurrency, $userMoney)
65-
// } label: {
66-
// VStack(alignment: .leading) {
67-
// Text(cryptocurrency.completeName)
68-
// .bold()
69-
// Text("Current Amount: \(formatDouble(value: cryptocurrency.amount))")
70-
// Text("Current Price: \("$" + formatDouble(value: cryptocurrency.price))")
71-
// }
72-
// }
73-
// }
74-
// }
75-
// .padding(.top, 5)
76-
// .padding(.bottom, 5)
7759
}
7860

7961
var body: some View {
@@ -90,16 +72,20 @@ struct VirtualTradingView: View {
9072
Divider()
9173
.background(.black)
9274

93-
HStack{
75+
HStack {
9476
Image("Dollar")
9577
.resizable()
9678
.scaledToFit()
9779
.frame(width: 50, height: 50)
98-
Text("Current Money: \("$" + formatDouble(value: userMoney))")
99-
.bold()
100-
.italic()
101-
.foregroundColor(.black)
102-
.font(.system(size: 20, weight: .light, design: .default))
80+
Button {
81+
82+
} label: {
83+
Text("Current Money: \("$" + formatDouble(value: userMoney))")
84+
.bold()
85+
.italic()
86+
.foregroundColor(.black)
87+
.font(.system(size: 20, weight: .light, design: .default))
88+
}
10389
}
10490
.padding(.top, 5)
10591
.padding(.bottom, 5)
@@ -125,8 +111,11 @@ struct VirtualTraidingView_Previews: PreviewProvider {
125111
Cryptocurrency(symbol: "BTC/USD", name: "Bitcoin", history: [], abbreviation: "BTC")
126112
]
127113
static let abbreviations = ["BNB", "BTC"]
114+
115+
@State static var userMoney: Double = 5000
116+
@State static var unknownErrorAlert: Bool = false
128117

129118
static var previews: some View {
130-
VirtualTradingView(cryptocurrencies: $cryptocurrencies, abbreviations: abbreviations)
119+
VirtualTradingView(cryptocurrencies: $cryptocurrencies, abbreviations: abbreviations, userMoney: $userMoney, unknownErrorAlert: $unknownErrorAlert)
131120
}
132121
}

0 commit comments

Comments
 (0)