Josh O'Connor
Josh O'Connor

Reputation: 4962

WKWebView loading html code instead of contents (iOS)

I am trying to load the following html file: https://dev-attachments-public.clickup.com/d23cdacd-510c-440e-818f-1e0f4d1a10bd/Email.html into my WKWebView doing the following:

let targetURL = NSURL(string: htmlFile)
let webView = WKWebView(frame: paddingView.bounds)
let request = NSURLRequest(url: targetURL as URL)
webView.load(request as URLRequest)

However, it only loads the code:

enter image description here

I'm not sure why this is occurring. Do I need to download this file locally then display it?

Upvotes: 0

Views: 683

Answers (2)

Josh O'Connor
Josh O'Connor

Reputation: 4962

This works:

var paths: [AnyObject] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [AnyObject]
let filePath: String = "\(paths[0])/\("index.html")"

if let url: NSURL = NSURL(string: htmlFile) {

    do {
        let urlData: NSData = try NSData(contentsOf: url as URL)
        urlData.write(toFile: filePath, atomically: true)

        webView.load(URLRequest(url: NSURL.fileURL(withPath: filePath)))

    } catch {
        print("Error:  Could not fetch fetchedResultsController")
    }
}

Upvotes: 0

Michael Hulet
Michael Hulet

Reputation: 3499

Notice that following that link on desktop also causes the file to be downloaded instead of displayed in a web browser. Looking at the headers for the request, your server is currently sending its Content-Type as application/octet-stream. This tells browsers (such as WKWebView) that this file is raw data and should be downloaded, displayed, and treated as such. Instead, you should send your Content-Type header as text/html, which tells browsers that it should render and display the HTML as a webpage. Furthermore, you should probably remove the Content-Disposition header to allow it to be its default of displaying inline as a webpage

Upvotes: 1

Related Questions