Learn Courses My Dashboard

Stock Tracker Trouble

Hello,
I am having trouble with the stock project, and I would appreciate any help & feedback. I am trying to incorporate data from the FMP website using the realtime company quotes api. The application builds, but doesn’t display anything either. Not sure what I am doing wrong or how I can populate a list of stocks? I am using module 2 lesson 12 as my reference for the stock project. I created a view, a view model, & a model(see below):

  //View  
    import SwiftUI

    struct StockListView: View {
        @ObservedObject var model = StockModel()
        
        var body: some View {
          
            VStack{
                List(model.stocks){ r in
                    
                    VStack(alignment: .leading){
                        Text(r.symbol).font(.title)
                    }
                }
            }
        }
    }

    struct StockListView_Previews: PreviewProvider {
        static var previews: some View {
            StockListView()
        }
    }
//ViewModel
    import Foundation

    class StockModel: ObservableObject{
        @Published var stocks = [Stocks]()
        
        init() {
            
          // Create URL Object
            let url = URL(fileURLWithPath: "https://financialmodelingprep.com/api/v3/quote/AAPL,FB?apikey=MyPersonalKey")
            
            //Error Handling
            do{
                //put the code that can throw an error
                //Create a data object with the data at the url
                let data = try Data(contentsOf: url)
                
                //parse the data
                let decoder = JSONDecoder()
                
                do{
                   let stockData =  try decoder.decode([Stocks].self, from: data)
                    
                   //set UUID for each instance
                    for r in stockData{
                        r.id = UUID()
                        
                    }
                    
                    //assign the data to the published property
                   self.stocks = stockData
                    
                }catch{
                    print(error)
                }
                
               
                
            }catch{
                //execution will come here if error is thrown
                print(error)
            }
            
            
           
        }
    }
//Model
    import Foundation

    class Stocks: Identifiable, Decodable {

    var id : UUID?

    var symbol: String

    var name : String

    var price : Double

    var changesPercentage : Double

    var change : Double

    var dayLow : Double

    var dayHigh : Double

    var yearHigh : Double

    var yearLow : Double

    var marketCap : Double

    var priceAvg50 : Double

    var priceAvg200 : Double

    var volume : Double

    var avgVolume : UInt64

    var exchange : String

    var open : Double

    var previousClose : Double

    var eps : Double

    var pe : Double

    var earningsAnnouncement : String

    var sharesOutstanding : UInt64

    var timestamp : UInt64

    }

Why doesn’t this code populate a list of stocks?

Are you getting an error? From your view model

I would recommend making a function like getData And call that in the onAppear modifier in your view rather than putting everything in the initializer

No, oddly I am not getting any errors so ever which makes it hard to troubleshoot. I started making a function to handle the connection…

I’ve only used the follow code to request local json object/files:
let pathString = Bundle.main.path(forResource: “recipes”, ofType: “json”)

Is there a method for Bundle.main.path that allows connects to external APIs?

I don’t know how you approach API parsing. I think in class StockModel i don’t see any URLSession code where you will initiate session with data task to get data, response and error from URL.

1 Like

No, bundle.main.path refers to files that you have in your project.

You should be creating a URL object from a string and then perform a data task to get data from that URL

You should look into these videos