Crash whille Converting NSURL to CFURL

2.2k Views Asked by At

I want to create pdf in document directory and want to give page numbers so I need CGPDFDocumentRef object.

let fileName: NSString = "test.pdf"

let path:NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)

let documentDirectory: AnyObject = path.objectAtIndex(0)

let pdfPathWithFileName = documentDirectory.stringByAppendingPathComponent(fileName as String)

UIGraphicsBeginPDFContextToFile(pdfPathWithFileName as String, CGRectZero, nil)

let ref : CGContextRef = UIGraphicsGetCurrentContext()!

let localUrl = NSURL.fileURLWithPath(pdfPathWithFileName)

I have converted file path in url but this below line generates a crash and I don't know why..?

let pdfDocumentRef: CGPDFDocumentRef = CGPDFDocumentCreateWithURL(localUrl as CFURLRef)!
3

There are 3 best solutions below

1
On

Its because your test.pdf is not present into document directory folder.

4
On

So it seems your NSURL(fileURLWithPath: pdfPathWithFileName) as CFURLRef part fails and that is what is causing your problems.

I just found this in the documentation about CFURL

CFURL fails to create an object if the string passed is not well-formed (that is, if it does not comply with RFC 2396). Examples of cases that will not succeed are strings containing space characters and high-bit characters. If a function fails to create a CFURL object, it returns NULL, which you must be prepared to handle. If you create CFURL objects using file system paths, you should use the CFURLCreateFromFileSystemRepresentation and CFURLCreateFromFileSystemRepresentationRelativeToBase functions, which handle the subtle differences between URL paths and file system paths.

And this question seems to be about the same problem. As one of the answers suggest:

You need the convert NSString to CFStringRef then call CFURLCreateWithFileSystemPath;

Hope that helps you.

2
On
 let localUrl  = pdfPathWithFileName as CFStringRef
 let pdfDocumentRef = CFURLCreateWithFileSystemPath(nil, localUrl, CFURLPathStyle.CFURLPOSIXPathStyle, false)
 let page_count = CGPDFDocumentGetNumberOfPages(pdfDocumentRef)