how to save website locally in WKWebView?

36 Views Asked by At

We want to show website using URL first and once its loaded how can we save data in cache or cookies so that afterwards even user goes offline it will load form that?

some solution we came across are:

  1. WKWebViewConfiguration().websiteDataTypes = [WKWebsiteDataTypeOfflineWebApplicationCache] - tho this methods does not work anymore
  2. can we save websites data locally (may be download its content - how?)

some ref: https://stackoverflow.com/a/53512299

1

There are 1 best solutions below

1
Navneet Kaur On

Please check the below code for fetching and saving the website data

 if let url = URL(string: "TYPE YOUR URL") {
        let request = URLRequest(url: url)
        webView.load(request)
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("Error: \(error)")
                return
            }
            
            if let data = data {
                self.saveDataLocally(data: data)
            }
        }
        task.resume()
    }

// Function to save data locally

func saveDataLocally(data: Data) {
    let fileManager = FileManager.default
    guard let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
        return
    }
    
    let htmlURL = documentsDirectory.appendingPathComponent("index.html")
    
    do {
        try data.write(to: htmlURL, options: .atomic)
    } catch {
        print("Error saving data: \(error)")
    }
}

To fetch the saved data you can use below mentioned code

let fileManager = FileManager.default
    guard let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
        return
    }
    let htmlURL = documentsDirectory.appendingPathComponent("index.html")
    if fileManager.fileExists(atPath: htmlURL.path) {
        if let htmlData = try? Data(contentsOf: htmlURL) {
            webView.load(htmlData, mimeType: "text/html", characterEncodingName: "UTF-8", baseURL: htmlURL)
        }
    } else {
        print("Website content not available locally.")
    }