Reputation: 2568
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?
Upvotes: 3
Views: 6200
Reputation: 6013
Swift 5+ Very Easy and Smooth Solution
let base64PDF = "m5hbWVfaWQiOiJ1aWQiLCJRSUQiOiIyNzg1ODYwNDM3NSIsIlVVSUQiOiIwMDE2M0U2Ri1EREMyLTFFRTktQUE5MS0wOEYxMDFEODU4NTYiLCJFbWFpbCI6IlNBSUYuUkVITUFOQEFBQlFBVEFSLkNPTSIs"
if let data = Data(base64Encoded: base64PDF, options: Data.Base64DecodingOptions.ignoreUnknownCharacters) as Data? {
self.webKitView.load(data, mimeType: "application/pdf", characterEncodingName: "", baseURL: nil)
}
Upvotes: -1
Reputation: 3225
For Swift 5, here a complete example with no force unwrapped and temporary file:
guard let data = Data(base64Encoded: base64), let fileUrl = try? saveTemporaryFile(from: data, filename: fileName) else {
// error handling
return
}
webView.load(data, mimeType: "application/pdf", textEncodingName: "", baseURL: fileUrl)
And the utility function to save the data in local temp file:
func saveTemporaryFile(from data: Data, filename: String? = nil) throws -> URL {
let filename = filename ?? UUID().uuidString
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(filename)
try? FileManager.default.removeItem(at: fileURL)
try data.write(to: fileURL)
return fileURL
}
Upvotes: 2
Reputation: 2596
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: ""))
}
Upvotes: 0
Reputation: 404
Try this
webView.load(data, mimeType: "application/pdf", textEncodingName: "utf-8", baseURL: URL(fileURLWithPath: ""))
Upvotes: 0
Reputation: 2568
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")!)
Upvotes: 3