3

I am using SwiftUI and I am trying to achieve a simple logical action but unable to understand SwiftUI action hierarchy.

I have one API call something like this,

final class TaskData: ObservableObject {

    @Published var updatedFields = false
    @Published var updateMsg = ""


    func updateFields()
    {
        //Some API Call
        .whenSuccess { (response) in
            DispatchQueue.main.async {
                self.updatedFields = true
                self.updateMsg = "Successfully updated fields"
                //Send Request to dismiss current View ???
            }
        }
    }
}

Now, I have a View something like this, and on a request I want to dismiss this View, but I am unable to find any method for that,

struct TaskView: View {

@Environment(\.presentationMode) var currentView: Binding<PresentationMode>
@EnvironmentObject var taskData: TaskData

var body : some View {

    //Some Views here ////

    //Need Some code here to dismiss currentView?????

    .navigationBarItems(trailing: Button(action: {

    }, label: {
        Text("Done")
    }).onTapGesture {
        self.taskData.updateFields() // Method Call to Update fields
    })
}

if someone can explain this thing in a little detail as I am newbie to SwiftUI, I have seen a lot tutorial but unable to understand this structure of swift.

Najam
  • 1,129
  • 11
  • 32

1 Answers1

1

It is not shown how TaskView is presented, but having presentationMode in give code snapshot let's assume that it is valid, so the approach might be as follows

@Environment(\.presentationMode) var presentationMode //better to name it same, 
                                                      //type is extracted from Environment
@EnvironmentObject var taskData: TaskData

var body : some View {

    //Some Views here ////
    SomeView()
        .onReceive(taskData.$updatedFields) { success in
           if success {
              self.presentationMode.wrappedValue.dismiss() // dismiss self
           }
        }
    ...
Asperi
  • 228,894
  • 20
  • 464
  • 690