How to Use SFSafariViewController NavigationItems in SwiftUI?

Hey everyone, I've come across a hurdle where I want to use the SFSafariViewController because it contains a navigation bar that fits the needs of my app with the ReaderView, Reload icon, share, and more. My issue though is that I'm displaying this SFSafariViewController through a SwiftUI NavigationLink, and the ViewController's navigation "done" bar button item won't pop my NavigationView. How do I go about programming that done button action to control a SwiftUI NavigationView? Would the Coordinator still be able to do this even if it's a navigation Bar item?

Replies

yes, it is possible to fix dismissal in this scenario (when "done" button is tapped), using a Coordinator as SFSafariViewControllerDelegate, here's a full example:

struct SafariView: UIViewControllerRepresentable {
    @Environment(\.dismiss) var dismiss

    let url: URL

    func makeUIViewController(context: Context) -> SFSafariViewController {
        let vc = SFSafariViewController(url: url)
        vc.preferredControlTintColor = .tintColor
        vc.delegate = context.coordinator
        return vc
    }

    func updateUIViewController(_ vc: SFSafariViewController, context: Context) {}

    class Coordinator: NSObject, SFSafariViewControllerDelegate {
        var dismissAction: DismissAction?

        func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
            dismissAction?()
        }
    }

    func makeCoordinator() -> Coordinator {
        let coordinator = Coordinator()
        coordinator.dismissAction = dismiss
        return coordinator
    }
}

This is a great solution, however the tappable area of the dismiss button (no matter if you use the .close or the default) is way too small. You can only tap on the very right edge of the word done. Any solution to this?

I have the same issue :( Don't know what to do with it