Search code examples
iosswiftuiwebviewswift4

Load UIImage into a WebView Swift 4


Rather than loading a WebView from a URL like this

override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: imageUrl.urlString)
    let request = URLRequest(url: url!)
    webView.load(request)

}

override func loadView() {
    let webConfiguration = WKWebViewConfiguration()
    webView = WKWebView(frame: .zero, configuration: webConfiguration)
    webView.uiDelegate = self

    view = webView
}

How can I load a UIImage onto the WebView in Swift 4?


Solution

  • Try Something like this.

    let html = "<html><img src=\"datadb/DestinationGuide/Images/YourImage.png\"/> </html>"
    
    //Save this html in `DocumentDirectory`
    let saveHTML = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("temp.html")
    
    try? html.data(using: .utf8)!.write(to: saveHTML)
    
    //Now load this `temp.html` file in webView
    webView.loadRequest(URLRequest(url: saveHTML))