Skip to content

Instantly share code, notes, and snippets.

@markvanwijnen
Created March 21, 2021 16:39
Show Gist options
  • Save markvanwijnen/4697fe0d10eaa764ec3e6e5d1c10b521 to your computer and use it in GitHub Desktop.
Save markvanwijnen/4697fe0d10eaa764ec3e6e5d1c10b521 to your computer and use it in GitHub Desktop.
import SwiftUI
import SafariServices
struct SafariView: UIViewControllerRepresentable {
class SafariViewControllerWrapper: UIViewController {
private var safariViewController: SFSafariViewController?
var url: URL? {
didSet {
if let safariViewController = safariViewController {
safariViewController.willMove(toParent: self)
safariViewController.view.removeFromSuperview()
safariViewController.removeFromParent()
self.safariViewController = nil
}
guard let url = url else { return }
let newSafariViewController = SFSafariViewController(url: url)
addChild(newSafariViewController)
newSafariViewController.view.frame = view.frame
view.addSubview(newSafariViewController.view)
newSafariViewController.didMove(toParent: self)
self.safariViewController = newSafariViewController
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.url = nil
}
}
typealias UIViewControllerType = SafariViewControllerWrapper
@Binding var url: URL?
func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SafariViewControllerWrapper {
return SafariViewControllerWrapper()
}
func updateUIViewController(_ safariViewControllerWrapper: SafariViewControllerWrapper,
context: UIViewControllerRepresentableContext<SafariView>) {
safariViewControllerWrapper.url = url
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment