Search code examples
iosswiftpdfuiwebview

Load PDF in UIWebView without baseURL


I have Data which represents a PDF. I get this from multiple sources (local storage and Firebase) so I have no baseURL. I tried to pass absoluteURL but it isn't working.

if let data = searchedSavedCarTest[sender as! Int].pdfData{

        let url = NSURL().absoluteURL
        dc.webView.load(data, mimeType: "application/pdf", textEncodingName: "", baseURL: url)
    }

the last line is causing an unexpectedly found nil.. error.

Is there any way to come around the baseURL?

(I am using Swift 3 and Xcode 8.1)


Solution

  • I haven't tried it in a real iOS environment yet, but I believe if you enter a valid URL it will solve the runtime error, and not really matter to the function of the code. Also, I would add the encoding (I inserted UTF-8 as an example but you should use the The IANA encoding name of your encoding).

        if let data = try? Data(contentsOf: URL.init(string: "http://www.orimi.com/pdf-test.pdf")!) {
    
        var wv = UIWebView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
        wv.load(data, mimeType: "application/pdf", textEncodingName: "UTF-8", baseURL: URL(string: "http://example.com")!)
    
        }