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

对着背影说爱祢 提交于 2020-01-22 01:10:24

问题


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: ""))
}


来源:https://stackoverflow.com/questions/43920284/how-to-load-a-pdf-from-a-base64-string-in-a-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!