0

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

pawello2222
  • 46,897
  • 22
  • 145
  • 209
user1974376
  • 141
  • 1
  • 8
  • Why don't you just pass the URL to the constructor? – JuJoDi Dec 31 '20 at 16:23
  • Does this answer your question https://stackoverflow.com/a/60019566/12299030? or this https://stackoverflow.com/a/60605529/12299030? – Asperi Dec 31 '20 at 16:24
  • You can't have an `@EnvironmentObject` inside an `ObservableObject` it is only for a SwiftUI `View`. You might be able to have a variable `var theBody: GlobalData` but not the actual `@EnvironmentObject`. – lorem ipsum Dec 31 '20 at 16:24

0 Answers0