I have a class that is used to get json data from a URL. I want to be able to change the path of the URL based on a property stored in an EnvironmentObject injected into the root view of my app. Apparently the class is not considered an ancestor of the root view. I get this error when I try to reference the EnvironmentObject in my class.
SwiftUI error thread 1: fatal error: no observableobject of type globaldata found. a view.environmentobject(_:) for globaldata may be missing as an ancestor of this view.
public class ImageFetcher: ObservableObject {
@Published var noteImages = [NoteImageData]()
@EnvironmentObject var theBody: GlobalData
init() {
load()
}
func load() {
let url = URL(string: "http://start of the path/(theBody.imagePath)/data.json")!
URLSession.shared.dataTask(with: url){(data,response,error) in
do {
if let d = data {
//print(String(decoding: d, as: UTF8.self))
let decodedLists = try JSONDecoder().decode([NoteImageData].self , from: d)
DispatchQueue.main.async {
self.noteImages = decodedLists
}
}else{
print("no data")
}
}
catch {
print("decoder error")
}
}
.resume()
}
}
How can I pass a slightly different path to that class based on a property stored in an EnvironmentObject? I have tried passing parameters to the class but that usually winds up with a complaint about the class not being instantiated yet. thanks
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…