changeset 400:6055a867d2b6

Implementing Historical Prices in Company.swift
author Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com>
date Sat, 15 May 2021 19:54:20 +0200
parents 5c99883c7964
children f843c6382529
files LazyBear.xcodeproj/project.pbxproj LazyBear.xcodeproj/project.xcworkspace/xcuserdata/dennis.xcuserdatad/UserInterfaceState.xcuserstate LazyBear/LazyBearApp.swift LazyBear/Views/Company/Chart.swift LazyBear/Views/Company/CompanyView.swift LazyBear/Views/Company/Helpers/ViewSelector.swift
diffstat 6 files changed, 60 insertions(+), 115 deletions(-) [+]
line wrap: on
line diff
--- a/LazyBear.xcodeproj/project.pbxproj	Sat May 15 12:31:40 2021 +0200
+++ b/LazyBear.xcodeproj/project.pbxproj	Sat May 15 19:54:20 2021 +0200
@@ -70,7 +70,6 @@
 		95E31C142647363800106B98 /* Chart.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95E31C132647363800106B98 /* Chart.swift */; };
 		95E31C16264736BE00106B98 /* DatePicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95E31C15264736BE00106B98 /* DatePicker.swift */; };
 		95E31C1826473A4D00106B98 /* CompanyHeader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95E31C1726473A4D00106B98 /* CompanyHeader.swift */; };
-		95E31C1C26473B5100106B98 /* ViewSelector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95E31C1B26473B5100106B98 /* ViewSelector.swift */; };
 		95FBE0DC2619CA7200440386 /* ProfileView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95FBE0DB2619CA7200440386 /* ProfileView.swift */; };
 /* End PBXBuildFile section */
 
@@ -161,7 +160,6 @@
 		95E31C132647363800106B98 /* Chart.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Chart.swift; sourceTree = "<group>"; };
 		95E31C15264736BE00106B98 /* DatePicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatePicker.swift; sourceTree = "<group>"; };
 		95E31C1726473A4D00106B98 /* CompanyHeader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CompanyHeader.swift; sourceTree = "<group>"; };
-		95E31C1B26473B5100106B98 /* ViewSelector.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewSelector.swift; sourceTree = "<group>"; };
 		95FBE0DB2619CA7200440386 /* ProfileView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfileView.swift; sourceTree = "<group>"; };
 /* End PBXFileReference section */
 
@@ -452,7 +450,6 @@
 		95E31C0E26472CB600106B98 /* Helpers */ = {
 			isa = PBXGroup;
 			children = (
-				95E31C1B26473B5100106B98 /* ViewSelector.swift */,
 				95E31C1726473A4D00106B98 /* CompanyHeader.swift */,
 				95E31C15264736BE00106B98 /* DatePicker.swift */,
 				95613AE0264FD34100D4CE8F /* NewsRow.swift */,
@@ -645,7 +642,6 @@
 			files = (
 				950C36E3260FB6180081CF53 /* HapticsManager.swift in Sources */,
 				95FBE0DC2619CA7200440386 /* ProfileView.swift in Sources */,
-				95E31C1C26473B5100106B98 /* ViewSelector.swift in Sources */,
 				95A5186A26185AAB0002D27C /* GenericRequest.swift in Sources */,
 				95A5188626186F590002D27C /* PriceView.swift in Sources */,
 				95613AE1264FD34100D4CE8F /* NewsRow.swift in Sources */,
Binary file LazyBear.xcodeproj/project.xcworkspace/xcuserdata/dennis.xcuserdatad/UserInterfaceState.xcuserstate has changed
--- a/LazyBear/LazyBearApp.swift	Sat May 15 12:31:40 2021 +0200
+++ b/LazyBear/LazyBearApp.swift	Sat May 15 19:54:20 2021 +0200
@@ -13,7 +13,7 @@
 
     var body: some Scene {
         WindowGroup {
-            ContentView()
+            CompanyView(symbol: "aapl")
                 .environment(\.managedObjectContext, persistenceController.container.viewContext)
         }
     }
--- a/LazyBear/Views/Company/Chart.swift	Sat May 15 12:31:40 2021 +0200
+++ b/LazyBear/Views/Company/Chart.swift	Sat May 15 19:54:20 2021 +0200
@@ -9,78 +9,78 @@
 import StockCharts
 
 struct Chart: View {
-    var chartData: ChartResponse
+    @ObservedObject var company: Company
     var symbol: String
     
     // Date picker
     var ranges = ["1D", "5D", "1M", "3M", "6M", "1Y", "5Y"]
     @State private var selectedRange = "3M"
     
+    // Set recurrent price request
+    @State private var timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect()
     
     var body: some View {
-        let priceViewStyle = PriceViewStyle(
-            alignment: .leading,
-            priceFont: .headline,
-            priceFontWeight: .semibold,
-            percentFont: .body,
-            percentFontWeight: .medium
-        )
-        
-        VStack {
-            DatePicker(ranges: ranges, selectedRange: $selectedRange)
-            
-            RoundedRectangle(cornerRadius: 15)
-                .foregroundColor(Color(.secondarySystemBackground))
-                .frame(height: 270)
-                .overlay(
-                    VStack {
-                        HStack {
-                            if let quote = chartData.quote![symbol.uppercased()] {
-                                let latestPrice = quote.latestPrice ?? 0
-                                let changePercent = quote.changePercent ?? 0
-                                PriceView(latestPrice: latestPrice, changePercent: changePercent, style: priceViewStyle)
+        if company.showChartView {
+            VStack {
+                DatePicker(ranges: ranges, selectedRange: $selectedRange)
+                    .onChange(of: selectedRange, perform: { value in
+                        print(value.lowercased())
+                    })
+                
+                RoundedRectangle(cornerRadius: 15)
+                    .foregroundColor(Color(.secondarySystemBackground))
+                    .frame(height: 270)
+                    .overlay(
+                        VStack {
+                            HStack {
+                                if let quote = company.chartData.quote![symbol.uppercased()] {
+                                    let latestPrice = quote.latestPrice ?? 0
+                                    let changePercent = quote.changePercent ?? 0
+                                    let priceViewStyle = PriceViewStyle(
+                                        alignment: .leading,
+                                        priceFont: .headline,
+                                        priceFontWeight: .semibold,
+                                        percentFont: .body,
+                                        percentFontWeight: .medium
+                                    )
+                                    PriceView(latestPrice: latestPrice, changePercent: changePercent, style: priceViewStyle)
+                                }
+                                Spacer()
                             }
-                            Spacer()
-                        }
-                        .padding([.top, .leading, .trailing])
-                        
-                        if let intradayPrices = chartData.intradayPrices![symbol.uppercased()] {
-                            if let prices = intradayPrices.compactMap { $0.open } {
-                                LineChartView(data: prices,
-                                              dates: nil,
-                                              hours: nil,
-                                              dragGesture: true
-                                )
-                                    .padding(.bottom)
+                            .padding([.top, .leading, .trailing])
+                            
+                            if let intradayPrices = company.chartData.intradayPrices![symbol.uppercased()] {
+                                if let prices = intradayPrices.compactMap { $0.open } {  // Map without nil
+                                    LineChartView(data: prices, dates: nil, hours: nil, dragGesture: true)
+                                        .padding(.bottom)
+                                }
                             }
                         }
+                    )
+                
+                if let latestNews = company.chartData.latestNews {
+                    ForEach(latestNews, id: \.self) { new in
+                        NewsRow(new: new)
                     }
-                )
-            
-            if let latestNews = chartData.latestNews {
-                ForEach(latestNews, id: \.self) { new in
-                    NewsRow(new: new)
                 }
             }
+            .onAppear { self.timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect() }  // Start timer
+            .onDisappear { self.timer.upstream.connect().cancel() }  // Stop timer
+            .onReceive(timer) { _ in
+                let url = "https://api.lazybear.app/company/chart/type=streaming/symbol=\(symbol)"
+                company.request(url, isInitRequest: false, "chart") }  // Receive timer notification
+        } else {
+            ProgressView()
+                .onAppear {
+                    let url = "https://api.lazybear.app/company/chart/type=init/symbol=\(symbol)"
+                    company.request(url, isInitRequest: true, "chart")
+                }
         }
     }
 }
 
 struct Chart_Previews: PreviewProvider {
     static var previews: some View {
-        Chart(
-            chartData: ChartResponse(
-                intradayPrices: ["AAPL": [IntradayPriceModel(open: 120.3)]],
-                quote: ["aapl": QuoteModel(changePercent: 0.03, companyName: "Apple Inc", latestPrice: 120.3)],
-                latestNews: [LatestNewsModel(
-                                datetime: 1621037430000,
-                                headline: "Chaos Monkeys' author calls Apple's statement on his departure defamatory",
-                                image: "https://cloud.iexapis.com/v1/news/image/99abeb99-6d9e-47c8-ae7b-53404eacccec",
-                                source: "Investing.com",
-                                summary: "https://www.investing.com/news/stock-market-news",
-                                url: "https://cloud.iexapis.com/v1/news/article/99abeb99-6d9e-47c8-ae7b-53404eacccec")]),
-            
-            symbol: "aapl"
-        )
+        Chart(company: Company(), symbol: "aapl")
     }
 }
--- a/LazyBear/Views/Company/CompanyView.swift	Sat May 15 12:31:40 2021 +0200
+++ b/LazyBear/Views/Company/CompanyView.swift	Sat May 15 19:54:20 2021 +0200
@@ -12,11 +12,10 @@
     var symbol: String
     
     @ObservedObject var company = Company()
-    @ObservedObject var viewSelector = ViewSelector()
     @State private var showViewSelector = false
     
-    // Set recurrent price request
-    @State private var timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect()
+    // Views
+    @State private var showChartView = true
     
     var body: some View {
         NavigationView {
@@ -24,23 +23,9 @@
                 VStack {
                     CompanyHeader(symbol: symbol, showViewSelector: $showViewSelector)
                     
-                    // <--- Chart View --->
-                    if viewSelector.views["chart"]! {
-                        let url = "https://api.lazybear.app/company/chart/type=init/symbol=\(symbol)"
-                        
-                        if company.showChartView {
-                            Chart(chartData: company.chartData, symbol: symbol)
-                                .onAppear { self.timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect() }  // Start timer
-                                .onDisappear { self.timer.upstream.connect().cancel() }  // Stop timer
-                                .onReceive(timer) { _ in
-                                    let url = "https://api.lazybear.app/company/chart/type=streaming/symbol=\(symbol)"
-                                    company.request(url, isInitRequest: false, "chart") }  // Receive timer notification
-                        }
-                        else {
-                            ProgressView()
-                                .onAppear { company.request(url, isInitRequest: true, "chart") } }
-                        
-                        // ---> Chart View <---
+                    // Chart View
+                    if showChartView {
+                        Chart(company: company, symbol: symbol)
                     }
                 }
                 .padding()
@@ -50,7 +35,7 @@
         }
         .actionSheet(isPresented: $showViewSelector) {
             ActionSheet(title: Text("Select an option"), buttons: [
-                .default(Text("Chart & News")) { viewSelector.showView(.chart) }, 
+                .default(Text("Chart & News")) { showChartView = true },
                 .cancel()
             ])
         }
--- a/LazyBear/Views/Company/Helpers/ViewSelector.swift	Sat May 15 12:31:40 2021 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-//
-//  ViewType.swift
-//  LazyBear
-//
-//  Created by Dennis Concepción Martín on 8/5/21.
-//
-
-import SwiftUI
-
-
-class ViewSelector: ObservableObject {
-    @Published var views = [
-        "chart": true
-    ]
-    
-    enum ViewType {
-        case chart
-    }
-    
-    func showView(_ viewType: ViewType) {
-        switch viewType {
-        case .chart:
-            toogleVariables()
-            views["chart"] = true
-        }
-    }
-    
-    /*
-     Change to false views
-     */
-    private func toogleVariables() {
-        for view in views.keys {
-            views[view] = false
-        }
-    }
-}