Crash whille Convert NSURL to CFURL

I want to create pdf in the document directory and want to provide page numbers, so I need a 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 converted the file path to url, but this line below causes crashes, and I don't know why ..?

 let pdfDocumentRef: CGPDFDocumentRef = CGPDFDocumentCreateWithURL(localUrl as CFURLRef)! 
+5
source share
3 answers

Because your test.pdf not in the document directory folder.

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

So it seems that your part of NSURL(fileURLWithPath: pdfPathWithFileName) as CFURLRef is failing and this is causing problems.

I just found this in the CFURL documentation

CFURL does not create an object if the string passed in is not correct (that is, if it does not comply with RFC 2396). Examples of cases that will not succeed are strings containing whitespace and high-bit characters. If the function does not create a CFURL object, it returns NULL, which you should be prepared to handle. If you create CFURL objects using file system paths, you must use the functions CFURLCreateFromFileSystemRepresentation and CFURLCreateFromFileSystemRepresentationRelativeToBase, 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 :

You need to convert NSString to CFStringRef, then call CFURLCreateWithFileSystemPath;

Hope this helps.

0
source

All Articles