Mercurial > public > lazybear
view 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 |
line wrap: on
line source
// // RequestPrices.swift // LazyBear // // Created by Dennis Concepción Martín on 3/1/21. // import SwiftUI class Price: ObservableObject { @Published var result = [PriceModel]() @Published var showingView = false @Published var showingAlert = false func request(symbol: String) { guard let url = URL(string: priceUrl(symbol: symbol, sandbox: true)) else { // Change sandbox when production print("Invalid URL") return } let request = URLRequest(url: url) URLSession.shared.dataTask(with: request) { data, response, error in if let data = data { if let decodedResponse = try? JSONDecoder().decode([PriceModel].self, from: data) { // we have good data – go back to the main thread DispatchQueue.main.async { // update our UI self.result = decodedResponse print("API request ok") // Check if data is empty if self.result.isEmpty || self.result.count <= 1 { print("Data is empty") self.showingView = false self.showingAlert = true } else { print("Showing view...") self.showingView = true } } // everything is good, so we can exit return } } // if we're still here it means there was a problem print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")") }.resume() } }