iosswiftsafariswiftui

How do I use SFSafariViewController with SwiftUI?


I'm trying to present a SFSafariViewController from a NavigationButton but I'm not sure how to do that with SwiftUI.

In UIKit, I would just do:

let vc = SFSafariViewController(url: URL(string: "https://google.com"), entersReaderIfAvailable: true)
    vc.delegate = self

    present(vc, animated: true)

Solution

  • Supplemental to Matteo Pacini post, .presentation(Modal()) was removed by iOS 13's release. This code should work (tested in Xcode 11.3, iOS 13.0 - 13.3):

    import SwiftUI
    import SafariServices
    
    struct ContentView: View {
        // whether or not to show the Safari ViewController
        @State var showSafari = false
        // initial URL string
        @State var urlString = "https://duckduckgo.com"
    
        var body: some View {
            Button(action: {
                // update the URL if you'd like to
                self.urlString = "https://duckduckgo.com"
                // tell the app that we want to show the Safari VC
                self.showSafari = true
            }) {
                Text("Present Safari")
            }
            // summon the Safari sheet
            .sheet(isPresented: $showSafari) {
                SafariView(url:URL(string: self.urlString)!)
            }
        }
    }
    
    struct SafariView: UIViewControllerRepresentable {
    
        let url: URL
    
        func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SFSafariViewController {
            return SFSafariViewController(url: url)
        }
    
        func updateUIViewController(_ uiViewController: SFSafariViewController, context: UIViewControllerRepresentableContext<SafariView>) {
    
        }
    
    }