I am trying to pre-load a WKWebView before the SecondVC is called/presented.
Can this be accomplished in the swift 5 programming language? Perhaps calling layoutSubviews()?
is it possible to preload a webView before transitioning to the next view controller? OR is the only way to show this is loading is through activity indicators?
First VC:
override func viewDidLoad() {
super.viewDidLoad()
SecondVC.loadWebView() //PSUEDO of what I am trying to do
}
SecondVC:
func loadWebView() {
// WKWebView nit
webView.navigationDelegate = self
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
view.addSubview(webView)
view.backgroundColor = .systemBackground
guard let url = URL(string: "https://connect.stripe.com/oauth/authorize?response_type=code&client_id=\(live_client_id)&scope=read_write") else {
return
}
webView.load(URLRequest(url: url))
}
Let's say this is the view controller where you have your web view. You can put the code where you load the webpage inside its initializer.
class WebViewController: UIViewController {
lazy private var webView: WKWebView = {
let webView = WKWebView(frame: view.bounds)
return webView
}()
private var url: URL!
init(url: URL) {
self.url = url
super.init(nibName: nil, bundle: nil)
self.loadWebsite()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private func loadWebsite() {
view.addSubview(webView)
webView.load(URLRequest(url: url))
}
}
And in the previous view controller, you instantiate the WebViewController
prior to navigating to the web view. When you instantiate it, the initializer of the WebViewController
is called and in turn loadWebsite()
method which loads the web page.
class ViewController: UIViewController {
let vc = WebViewController(url: URL(string: "https://stripe.com/")!)
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.showWebView()
}
}
private func showWebView() {
navigationController?.show(vc, sender: nil)
}
}
So by the time you actually show the WebViewController
, hopefully the webpage will be already loaded.