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

2020-04-28 12:10发布

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?

3条回答
时光不老,我们不散
2楼-- · 2020-04-28 12:42

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")!)
查看更多
成全新的幸福
3楼-- · 2020-04-28 12:50

Try this

webView.load(data, mimeType: "application/pdf", textEncodingName: "utf-8", baseURL: URL(fileURLWithPath: ""))
查看更多
手持菜刀,她持情操
4楼-- · 2020-04-28 12:50

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: ""))
}
查看更多
登录 后发表回答