iospdf

Opening a PDF file in Files app returns nil


I want to open a pdf file that sits in the Files app on an iOS Device. I have setup everything so when the user selects to open the pdf file with my app the following function gets called:

-( BOOL )application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options


The path to the file is as below:

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

however when I go to read the file in my swift code using the following code it returns nil

let pdfDoc = CGPDFDocument( pdfURL )

Any ideas
Thanks Reza


Solution

  • The URL is security-scoped bookmarked so one needs to wrap it in url accessing code:

    if pdfURL.startAccessingSecurityScopedResource() {
    
        let pdfDoc = CGPDFDocument( pdfURL )
        // additional executions
        pdfURL.stopAccessingSecurityScopedResource()
    }