iOS Swift SFSafariViewController update new URL and refresh view

1.6k Views Asked by At

I'm using SFSafariViewController for load weblinks,
In my case first I need to open one URL after some process/time(like 10 sec) I need to update my URL in the same tab and refresh SFSafariViewController.

if let url = URL(string: "Google.com") {
    let VC= SFSafariViewController(url: url)
    VC.delegate = self
    self.present(VC, animated: true, completion: nil)
}

There is any way to update The URL and refresh the current SFSafariViewController page?

2

There are 2 best solutions below

0
On BEST ANSWER

SFSafariViewController is specifically designed to present web content that your application cannot interact with. From the documentation:

The user's activity and interaction with SFSafariViewController are not visible to your app, which cannot access AutoFill data, browsing history, or website data.

More specifically related to your question, the documentation for SFSafariViewController also says:

If your app customizes, interacts with, or controls the display of web content, use the WKWebView class.

Since you want to control the display of the web content (changing the URL) you should probably use WKWebView.

0
On

Using WKWebView to solve the problem.

class webViewController: WKNavigationDelegate, WKUIDelegate {
    var webview: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        webview = WKWebView(frame: self.view.bounds)
        self.view.addSubview(webview)
        webview.navigationDelegate = self
        webview.uiDelegate = self
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let url = navigationAction.request.url {
            // Dosomthing()
            decisionHandler(.cancel)
            return
        }
        decisionHandler(.allow)
    }
    
    func Dosomthing() {
        self.webview.load(URLRequest(url: newURL))
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            self.webview.reload()
        }
    }
}