Created
March 21, 2021 16:39
-
-
Save markvanwijnen/4697fe0d10eaa764ec3e6e5d1c10b521 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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