I am fetching PDF data. It provides me URL, and when I am converting it to base64. This is what I am getting:
The file “file.pdf” couldn’t be opened because you don’t have permission to view it.
I am not getting why is it giving this. This is how I am getting the pdf file url:
@State var openPDF = false
@State var fileName = ""
@State var pdfFile : URL?
var body: some View {
Button {
self.openPDF.toggle()
}, label {
Text("Add Attachment")
}.fileImporter(isPresented: $vm.openPDF, allowedContentTypes: [.pdf]) { result in
do {
let fileURL = try result.get()
print(fileURL)
self.fileName = fileURL.lastPathComponent
self.pdfFile = fileURL
} catch {
print("error getting documents")
print(error.localizedDescription)
}
}
}
An this is how I am converting it to base64:
do {
let filePath = pdfFile
let fileData = try Data.init(contentsOf: filePath!)
let fileStream:String = fileData.base64EncodedString()
print(fileStream)
} catch {
print("error")
print(error.localizedDescription)
}
In this do-catch, it is giving the error that "this file could not be opened because you don’t have permission.
2
Answers
Do this to convert PDF to Base64 String:
My Code for converting PDF to Base64String
Here fileName is State variable and base64PDF is also a State variable
I have used If condition before fileurl because it is giving error