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

2020-04-28 11:54发布

问题:

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?

回答1:

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")!)


回答2:

Try this

webView.load(data, mimeType: "application/pdf", textEncodingName: "utf-8", baseURL: URL(fileURLWithPath: ""))


回答3:

First convert the base64String to NSData and then convert to Data and use it.

PDF files are binary files so they can't be represented as UITF8 encoded string directly.

if let data = NSData(base64Encoded: base64String, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) as Data? {
    self.webView.load(data, mimeType: "application/pdf", characterEncodingName: "", baseURL: URL(fileURLWithPath: ""))
}