Search code examples
iosswiftiphoneswiftuiswift3

How to trigger onAppear when returning from fullScreenCover


onAppear doesn't trigger

struct ProfileView: View {
    @StateObject var viewModel = ProfileViewViewModel()
    var body: some View {
        NavigationView {
            VStack {
                if let user = viewModel.user {
                    profile(user: user)
                } else {
                    Text("Loading Profile...")
                }
            }
            .navigationTitle("Profile")
        }
        .onAppear {
            viewModel.fetchUser() //this is the problem
        }
        .fullScreenCover(isPresented: $viewModel.showingPreview) {
            PreviewAvatarView()
        }
    }
}

I realized that onAppear didn't trigger when I dismiss fullscreencover.


Solution

  • The onAppear doesn’t trigger because your underlying view is not appearing – the view that is covering it is going away, which isn’t the same thing.

    However, fullScreenCover has a rarely-used optional argument, onDismiss, which may fulfil your needs, e.g.:

    .fullScreenCover(
      isPresented: $viewModel.showingPreview,
      onDismiss: { viewModel.fetchUser() }
    ) {
      PreviewAvatarView()
    }
    

    Apple documentation