Search code examples
iosswiftpdfswift3uiwebview

How to load a PDF from a Base64 string in a UIWebView


I'm using an API that is returning a Base64 string, something like this:

data:application/pdf;base64,**BASE64STRING**

Where BASE64STRING is what I need to display the PDF.

So far I only created a Data object that gets the Base64 string:

let data = Data(base64Encoded: BASE64STRING)

And I tried to load it in the webview:

webView.load(data!, mimeType: "application/pdf", textEncodingName: "", baseURL: URL(string: "")!)

The problem is that I don't have a local PDF file, so I don't know what I should put in baseURL. Currently it's giving me a fatal error: unexpectedly found nil while unwrapping an Optional value

How can I load the PDF in the webView? Is there any better way to do that?


Solution

  • I solved the problem, despite that I'm not sure if it's a good approach, the solution is to put any valid URL in baseUrl:

    webView.load(data!, mimeType: "application/pdf", textEncodingName: "", baseURL: URL(string: "https://www.google.com")!)