comparison Simoleon/Conversion.swift @ 19:94fd7ac93060

Redesign
author Dennis Concepción Martín <dennisconcepcionmartin@gmail.com>
date Sun, 18 Jul 2021 20:00:05 +0100
parents
children c3dda63f50ed
comparison
equal deleted inserted replaced
18:a3512b689bbe 19:94fd7ac93060
1 //
2 // Conversion.swift
3 // Simoleon
4 //
5 // Created by Dennis Concepción Martín on 18/07/2021.
6 //
7
8 import SwiftUI
9 import Alamofire
10
11 struct Conversion: View {
12 @State private var mainCurrency = "USD"
13 @State private var secondaryCurrency = "GBP"
14 @State private var amountToConvert = "1000"
15 @State private var price: Double = 1.00
16 @State private var showingConversion = false
17 @State private var showingCurrencySelector = false
18 @State private var selectingMainCurrency = false
19 @State private var currencyPairNotFound = false
20
21 let currencyMetadata: [String: CurrencyMetadataModel] = parseJson("CurrencyMetadata.json")
22
23 var body: some View {
24 ScrollView(showsIndicators: false) {
25 VStack(alignment: .leading) {
26 HStack {
27 Button(action: { selectingMainCurrency = true; showingCurrencySelector = true }) {
28 CurrencyButton(currency: $mainCurrency)
29 }
30
31 Button(action: { selectingMainCurrency = false; showingCurrencySelector = true }) {
32 CurrencyButton(currency: $secondaryCurrency)
33 }
34 }
35
36 ConversionBox(
37 mainCurrency: $mainCurrency,
38 secondaryCurrency: $secondaryCurrency,
39 amountToConvert: $amountToConvert,
40 price: $price,
41 showingConversion: $showingConversion,
42 showingCurrencySelector: $showingCurrencySelector,
43 currencyPairNotFound: $currencyPairNotFound
44 )
45 }
46 .padding()
47 .onAppear { requestApi(mainCurrency, secondaryCurrency) }
48 .onChange(of: showingCurrencySelector, perform: { showingCurrencySelector in
49 if !showingCurrencySelector {
50 requestApi(mainCurrency, secondaryCurrency)
51 }
52 })
53 .sheet(isPresented: $showingCurrencySelector) {
54 CurrencySelector(
55 mainCurrencySelected: $mainCurrency,
56 secondaryCurrencySelected: $secondaryCurrency,
57 showingCurrencySelector: $showingCurrencySelector,
58 selectingMainCurrency: $selectingMainCurrency
59 )
60 }
61 }
62 .navigationBarHidden(true)
63 }
64
65 private func requestApi(_ mainCurrency: String, _ secondaryCurrency: String) {
66 let url = "https://api.1forge.com/quotes?pairs=\(mainCurrency)/\(secondaryCurrency)&api_key=BFWeJQ3jJtqqpDv5ArNis59pAlFcQ4KF"
67
68 AF.request(url).responseDecodable(of: [CurrencyQuoteModel].self) { response in
69 self.showingConversion = false
70 self.currencyPairNotFound = false
71
72 if let currencyQuotes = response.value {
73 if let price = currencyQuotes.first?.price {
74 self.price = price
75 self.showingConversion = true
76 } else {
77 self.currencyPairNotFound = true
78 }
79 } else {
80 // Handle error
81 }
82 }
83 }
84 }
85
86
87 struct Conversion_Previews: PreviewProvider {
88 static var previews: some View {
89 NavigationView {
90 Conversion()
91 }
92 }
93 }