Created
March 8, 2021 18:00
-
-
Save markvanwijnen/1cf3dd1f66604ad8c7b17eff3fd9d763 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 { | |
// 1 | |
class SafariViewControllerWrapper: UIViewController { | |
// 2 | |
private var safariViewController: SFSafariViewController? | |
// 3 | |
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 | |
// 4 | |
@Binding var url: URL? | |
// 5 | |
func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SafariViewControllerWrapper { | |
return SafariViewControllerWrapper() | |
} | |
// 6 | |
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