Mercurial > public > lazybear
view lazybear/Views/Price.swift @ 115:33e03e2863f6
Implementing TabView
author | Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com> |
---|---|
date | Thu, 04 Feb 2021 20:36:33 +0100 |
parents | 4c172ff9af20 |
children | 4e920489a57e |
line wrap: on
line source
// // Price.swift // LazyBear // // Created by Dennis Concepción Martín on 27/1/21. // import SwiftUI import CloudKit struct Price: View { @State var symbol: String @State var showVertical: Bool @EnvironmentObject var apiAccess: ApiAccess // <--------- API Job ---------> @State private var url = String() { didSet { requestPrice() }} @State private var showingView = false @State private var data = [QuoteModel]() { didSet { self.showingView = true }} // <--------- API Job ---------> // Set recurrent price request. Real-time prices let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() var body: some View { VStack(alignment: .trailing) { if self.showingView { Group { Text("\(data[0].latestPrice ?? 0, specifier: "%.2f")") .fontWeight(.semibold) Text("\(data[0].changePercent ?? 0 * 100, specifier: "%.2f")%") .font(.subheadline) .foregroundColor(.white) .background(percentageColor().cornerRadius(5)) } .if(showVertical) { content in HStack { content } } } } .onAppear { getUrl() } //.onReceive(timer) { _ in requestPrice() } .onDisappear { self.timer.upstream.connect().cancel() } // Stop timer } private func getUrl() { // 1 -> Sandbox / 2 -> Production let baseUrl = apiAccess.results[1].url ?? "" let token = apiAccess.results[1].key ?? "" let path = "/stable/stock/\(symbol)/quote?token=" self.url = baseUrl + path + token } private func requestPrice() { request(url: url, model: QuoteModel.self) { result in self.data = [QuoteModel(latestPrice: result.latestPrice, changePercent: result.changePercent)] } } private func percentageColor() -> Color { var color: Color = .red if data[0].changePercent ?? 0 >= 0 { color = .green } return color } } // Wrap content if some condition is satisfied extension View { @ViewBuilder func `if`<Content: View>(_ conditional: Bool, content: (Self) -> Content) -> some View { if conditional { content(self) } else { self } } } struct Price_Previews: PreviewProvider { static var previews: some View { Price(symbol: "AAPL", showVertical: false) } }