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?