-2

I have used .fileImporter to import a pdf url from the local device into my swiftui app. Now I wish to convert to data and save.

.fileImporter(isPresented: $isPresented, allowedContentTypes: [.pdf]) { result in
    switch result {
    case .success(let url):
        if let pDFDocument = PDFDocument(url: url) {
            // this is nil
            if let data = pDFDocument.dataRepresentation() {
                // save data
            }
        }
    case .failure(let error):
        print(error)
    }
}

however this is not working. PDFDocument(url: url) is nil despite the file just having been picked from .fileImporter. The url follows the following pattern:

file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/Documents/etc...

I'm guessing it's the private that's preventing access? If so how can I get a pdf file into my app and use it?

I'm wondering how I can get this to work

alionthego
  • 8,508
  • 9
  • 52
  • 125

1 Answers1

1

Using startAccessingSecurityScopedResource() solved this for me:

.fileImporter(isPresented: $isPresented, allowedContentTypes: [.pdf]) { result in
    switch result {
    case .success(let url):
        url.startAccessingSecurityScopedResource()
        if let pDFDocument = PDFDocument(url: url) {
            // this is nil
            if let data = pDFDocument.dataRepresentation() {
                // save data
            }
        }
    case .failure(let error):
        print(error)
    }
}

https://developer.apple.com/documentation/foundation/nsurl/1417051-startaccessingsecurityscopedreso

alionthego
  • 8,508
  • 9
  • 52
  • 125
  • `startAccessingSecurityScopedResource()` returns a `Bool`, so you should really only proceed if that’s `true`. In addition, once you've used the data contents, you should call `url.stopAccessingSecurityScopedResource()`. – ScottM Oct 27 '22 at 10:06