Learn Courses My Dashboard

Hmm... Error is tough

Hey y’all, I’m having another error again and I can’t fix it…
My error:

SwiftUI:0: Fatal error: No ObservableObject of type ModelData found. A View.environmentObject(_:) for ModelData may be missing as an ancestor of this view.
2021-07-20 14:32:29.128610-0700 Stocks[37907:1833380] SwiftUI:0: Fatal error: No ObservableObject of type ModelData found. A View.environmentObject(_:) for ModelData may be missing as an ancestor of this view.

My code: GitHub - HSSwift/StockApp

Please help me!

Where are you getting this error? Like which file and which line?

@HarriSN

In your GitHub repo ContentView.swift is missing. Without that nothing can be checked.

You could paste the code in a reply.

(edit)
It could be that you have not injected your enviromentObject in the parent view. Try doing this to your StocksApp.swift file:

@main
struct StocksApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(ModelData())
        }
    }
}

(Supplementary question)
What View is the opening View to your App? Is ContentView used at all?

It also looks like your struct does not match the data being returned from the API call.

That problem has gotten solved with your solution, but I have another error though that could be similar to the line in your reply:

Couldn't parse JSON as Stocks:
keyNotFound(CodingKeys(stringValue: "beta", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"beta\", intValue: nil) (\"beta\").", underlyingError: nil))
Couldn't parse JSON as Stocks:
keyNotFound(CodingKeys(stringValue: "beta", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"beta\", intValue: nil) (\"beta\").", underlyingError: nil))
Couldn't parse JSON as Stocks:
keyNotFound(CodingKeys(stringValue: "beta", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"beta\", intValue: nil) (\"beta\").", underlyingError: nil))

That’s because as I suggested, your JSON code returned from your API does not match the Model you have defined.

Capture a sample of your data by copying your url and add a quote item and your key and paste that into a new browser. Copy that json output and create your struct based on that data. Of course you will need to change the relevant property names you have used in your views.