【Xcode/SwiftUI】SafariServicesを使ってWebViewを表示させる

Webの画面をアプリで表示させる機能です、シンプルです。

実装

import SwiftUI
import SafariServices

struct SafariView: UIViewControllerRepresentable {
    let url: URL
    let onDismiss: (() -> Void)?

    func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SFSafariViewController {
        let safariViewController = SFSafariViewController(url: url)
        safariViewController.dismissButtonStyle = .done
        safariViewController.delegate = context.coordinator
        return safariViewController
    }

    func updateUIViewController(_ uiViewController: SFSafariViewController, context: UIViewControllerRepresentableContext<SafariView>) {
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator(onDismiss: onDismiss)
    }

    final class Coordinator: NSObject, SFSafariViewControllerDelegate {
        let onDismiss: (() -> Void)?

        init(onDismiss: (() -> Void)? = nil) {
            self.onDismiss = onDismiss
        }

        func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
            onDismiss?()
        }
    }
}
import SwiftUI

struct HomeView: View {
    let dismissAction: (() -> Void)
    @State private var showWebView = false
    private let url = URL(string: "http://abehiroshi.la.coocan.jp/")

    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(
                    destination: SafariView(url: url!, onDismiss: { showWebView = false })
                        .navigationBarHidden(true)
                        .ignoresSafeArea(),
                    isActive: $showWebView
                ) {
                    Button(action: {
                        showWebView = true
                    }, label: {
                        Text("Show WebView")
                            .font(.system(size: 32, weight: .bold))
                            .foregroundColor(.white)
                            .padding()
                            .background(Color.orange)
                    })
                }
            }
        }
    }
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView(
            dismissAction: {}
        )
    }
}