2

I found away of getting the types of content in a pdf. I built my code on this example where I am trying to read the content types from the dictionary. I found out that the key for type is Type. However I am getting an Error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Here is my code:

pdfDoc = CGPDFDocumentCreateWithURL(url)

if (pdfDoc != nil) {
    let pdfCatalog=CGPDFDocumentGetCatalog(pdfDoc)
    var uriStringRef: UnsafeMutablePointer< CGPDFStringRef>!

    if (CGPDFDictionaryGetString(pdfCatalog, "Type", uriStringRef)) { //error
        print(uriStringRef)

    }
}

The only nil parameter is uriStringRef. However from the example, I am not supposed to set to any value before passing to CGPDFDictionaryGetString, and according to Apple's documentation, this should get the string returned value based on the key "Type". Am I right?

How can I solve this problem?

Community
  • 1
  • 1
eskoba
  • 532
  • 1
  • 7
  • 25

1 Answers1

0

You are passing an uninitialized pointer to the CGPDFDictionaryGetString method, that is unsafe because you cannot know whether the method being called tries to read from a pointer before writing to it.

From the Swift blog post Interacting with C Pointers:

Pointers as In/Out Parameters

C and Objective-C don’t support multiple return values, so Cocoa APIs frequently use pointers as a way of passing additional data in and out of functions. Swift allows pointer parameters to be treated like inout parameters, so you can pass a reference to a var as a pointer argument by using the same & syntax.

For safety, Swift requires the variables to be initialized before being passed with &. This is because it cannot know whether the method being called tries to read from a pointer before writing to it.

So initialize the CGPDFStringRef 'pointer' like this:

var uriStringRef = CGPDFStringRef.init()

And pass it to the method using the inout syntax:

CGPDFDictionaryGetString(pdfCatalog, "Type", &uriStringRef)
Community
  • 1
  • 1
Kymer
  • 1,184
  • 8
  • 20