Search code examples
iosswiftpdfbase64

Convert PDF To Base64 in SwiftUI


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.


Solution

  • Do this to convert PDF to Base64 String:

    fileapp.startAccessingSecurityScopedResource() {
                defer {
                    DispatchQueue.main.async {
                        fileapp.stopAccessingSecurityScopedResource()
                    }
                }
                
                do {
                    
                    let fileData = try Data.init(contentsOf: fileapp)
                    let fileStream:String = fileData.base64EncodedString()
                    print(fileStream)
                    base64PDF = fileStream
                } catch {
                    print("error")
                    print(error.localizedDescription)
                }
            }