Create an object inside a View from input parameters

Hi All,

I'm trying to pass in a URL from a View (screen) and navigate to a new View, which then would take a URL to initialize an object.

I'd say it goes something like this:

//----- File 1 ---------//

struct myView1: View {

    var body: some View {

        HStack{
            Logo()
            NavigationLink(destination: myView2(url: url_passed_in)) {
                Circle()
            }
        }
    }
}
//-----end of file 1-----//

//------ File 2 ---------//

struct myView2: View {
    var url: URL
    private var myObject: SpecialObject // <-- I need to initialize this from the url passed in
   @State private var progress: Float
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
   var body: some View {
         ProgressView("Downloading...", value: progress, total: 100).onReceive(timer) { _ in
              progress = SpecialObject.get_progress()
        }
    }
}

//----- end of file 2-------------//

//------ File 3 ----------//

class SpecialObject {
    var url: URL
    @State private var progress: Float = 0.0

    init(url:URL) {
        // Code that takes the url of a file to create an object
    }

    func get_progress() -> Float {
        return progress
    }
}
// -----end of file 3 -----//

Long story short, I want to open an Audio file from the URL and process it...and update the UI with how far along it is in processing

I have tried several things and fixing one bug creates more bugs. Please help

Accepted Answer

I have tried several things and fixing one bug creates more bugs.

You should have shown what you have tried if you really want help from readers. Taking time to write an answer and being said "I have already tried it but it does not work" is a depressing experience.

Anyway, the right answer might depend on the parts you have not shown yet. You should better show more context to get better responses sooner.

Anyway, this is one thing you should try first:

struct MyView2: View {
    var url: URL
    private var myObject: SpecialObject
    @State private var progress: Float = Float()
    
    init(url: URL) {
        self.url = url
        self.myObject = SpecialObject(url: url)
    }
    
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    
    var body: some View {
        ProgressView("Downloading...", value: progress, total: 100).onReceive(timer) { _ in
            self.progress = self.myObject.get_progress()
        }
    }
}

(I renamed myView2 to MyView2. In Swift, type names should start with a Capital letter.)

If this does not solve your issue, please do not say simply it does not work, but provide as much info as you can about the context and the code you have tried.

Create an object inside a View from input parameters
 
 
Q