comparison Functions/Price.swift @ 0:668fd7e0d121

first commit
author Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com>
date Tue, 05 Jan 2021 16:43:09 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:668fd7e0d121
1 //
2 // RequestPrices.swift
3 // LazyBear
4 //
5 // Created by Dennis Concepción Martín on 3/1/21.
6 //
7
8 import SwiftUI
9
10 class Price: ObservableObject {
11 @Published var result = [PriceModel]()
12 @Published var showingView = false
13 @Published var showingAlert = false
14
15 func request(symbol: String) {
16 guard let url = URL(string: priceUrl(symbol: symbol, sandbox: true)) else { // Change sandbox when production
17 print("Invalid URL")
18 return
19 }
20 let request = URLRequest(url: url)
21 URLSession.shared.dataTask(with: request) { data, response, error in
22 if let data = data {
23 if let decodedResponse = try? JSONDecoder().decode([PriceModel].self, from: data) {
24 // we have good data – go back to the main thread
25 DispatchQueue.main.async {
26 // update our UI
27 self.result = decodedResponse
28 print("API request ok")
29
30 // Check if data is empty
31 if self.result.isEmpty || self.result.count <= 1 {
32 print("Data is empty")
33 self.showingView = false
34 self.showingAlert = true
35 } else {
36 print("Showing view...")
37 self.showingView = true
38 }
39
40 }
41
42 // everything is good, so we can exit
43 return
44 }
45 }
46
47 // if we're still here it means there was a problem
48 print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
49 }.resume()
50 }
51 }