Is it possible to reload a new url into WKWebView after initial loading?

Viewed 1570

I am using WKWebView in a simple ios 13 app. I want to be able to open another url based on a user interaction with my app.

Here is the code in my ViewController

    var url:String = "https://example.com";

    override func viewDidLoad() {
        let notificationName = Notification.Name("updateWebView")
        updateWebView()
    }

    @objc func updateWebView() {
        guard let url = URL(string: url) else {
            print("Invalid URL")
            return
        }
        let request = URLRequest(url: url)
        newWebView.load(request)
    }

I have set up in sceneDelegate code that updates the url in the view controller, looks something like so:

let yourViewController = self.window?.rootViewController as? ViewController
        yourViewController?.passData(newUrl) 

I can see the url string being updated in viewController class as a result with the debugger. However When It runs through the following code block:

    func passData(_ data : String?) {
        self.data = data
        guard let url = URL(string: url) else {
            print("Invalid URL")
            return
        }
        let request = URLRequest(url: url)
        newWebView.load(request)

    }

The console log the following message:

2019-10-15 20:33:28.886512+0100 SamplerApp[59216:7409192] [ProcessSuspension] 0x600000c936c0 - WKProcessAssertionBackgroundTaskManager: Ignored request to start a new background task because the application is already in the background

I would expect this to load the new url inside my WKWebView in my app but instead the code does not seem to do anything just log the message

2 Answers

All you have to do is go through WKWebView.evaluateJavaScript().

webView.evaluateJavaScript("window.location = 'https://www.google.com';", completionHandler: nil)

What this does is go through JavaScript instead of Swift. It 'fools' Swift into thinking that the webpage wants to go to a different URL.

Be sure to substitute webView for your own WKWebView and https://www.google.com for whatever website you want to redirect the user to.

By reading your title, I believe you're trying to load a new URL when the first URL is loaded.

Example:

on viewDidLoad() load "https://google.com", then when "https://google.com" is successfully loaded, you want to load other URL like "https://stackoverflow.com".

If that's really the case, you can just simply use the WKNavigationDelegate's function:

webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)

That function will be trigger when the URL is completely loaded.

Related