Home > Blockchain >  How to reload WKWebView?
How to reload WKWebView?

Time:12-27

I have an html document on my server. I am loading text from this document in my webview. But when I change text in html document in my server. My webview is not updating new text. I need to update my webview only when I load my view controller with webview. I am using this code for this but my webview is not updating:

import UIKit
import WebKit

class WayViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if let url = URL(string: "\(waysURL)") {
            let urlRequest = URLRequest(url: url)
            webView.load(urlRequest)
        }
                
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        webView.reload() 
    }
}

The problem is that if I closed the app. Then I updated the text on the server. Went back to the app, my text in the webview didn't update.

CodePudding user response:

The issue there is that you need to reloadFromOrigin to fetch the remote changes. You need also to set your url request cache policy. The default policy is useProtocolCachePolicy

"If a cached response does not exist for the request, the URL loading system fetches the data from the originating source."

So if the data already exists (that's your scenario) it does NOT fetch from the remote again.

What you need is to ignore the local cached data setting the url request to reloadIgnoringLocalCacheData

"This policy specifies that no existing cache data should be used to satisfy a URL load request."


import UIKit
import WebKit

class WayViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if let url = URL(string: "\(waysURL)") {
            let urlRequest: URLRequest = .init(
                url: url,
                cachePolicy: .reloadIgnoringLocalCacheData
            )
            webView.load(urlRequest)
        }    
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        webView.reloadFromOrigin() 
    }
}
  • Related