Search code examples
swiftuiwebkit

How to load a webpage in an ovally inside a SwiftUI App vs loading in safari


The functionality I'm looking to create is what the ESPN app does when you click on one of its alerts... it loads the app but instead of formatting the view it loads a Safari view over the app that can be tapped away (honestly I hate it in that instance but in ones like these it would work great.)

current code for reference

Button(action: {
                openURL(URL(string: "linkhere")!)
    }) {
                Image("LISTENMENU")
            }

Am I going to need to setup another view and build the webkitview myself or can this functionality be specified another way? (perhaps by tinkering with the openURL string


Solution

  • You need to wrap the SFSafariViewController (which is from UIKit) into SwiftUI, since it isn't possible to do this natively right now. You should use UIViewControllerRepresentable to do this.

    import SwiftUI
    import SafariServices
    
    struct MyView: View {
        @State var showStackoverflow:Bool = false
    
        var body: some View {
            Button(action: { self.showStackoverflow = true }) {
                Text("Open stackoverflow")
            }
            .sheet(isPresented: self.$showStackoverflow) {
                SFSafariViewWrapper(url: URL(string: "https://stackoverflow.com")!)
            }
        }
    }
    struct SFSafariViewWrapper: UIViewControllerRepresentable {
        let url: URL
        func makeUIViewController(context: UIViewControllerRepresentableContext<Self>) -> SFSafariViewController {
            return SFSafariViewController(url: url)
        }
        func updateUIViewController(_ uiViewController: SFSafariViewController, context: UIViewControllerRepresentableContext<SFSafariViewWrapper>) {
            return
        }
    }