崩溃whille将NSURL转换为CFURL

时间:2016-05-04 06:36:58

标签: ios swift nsurl cgcontextref

我想在文档目录中创建pdf,并且想要提供页码,所以我需要CGPDFDocumentRef对象。

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)

我已经在url中转换了文件路径,但是下面这行会导致崩溃,我不知道为什么......?

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

3 个答案:

答案 0 :(得分:0)

这是因为您的test.pdf不存在于文档目录文件夹中。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

所以看来你的NSURL(fileURLWithPath: pdfPathWithFileName) as CFURLRef部分失败了,这就是造成问题的原因。

我刚在documentation about CFURL

中找到了这个
  

如果传递的字符串格式不正确(即,如果它不符合RFC 2396),则CFURL无法创建对象。不成功的情况的示例是包含空格字符和高位字符的字符串。如果函数无法创建CFURL对象,则返回NULL,您必须准备好处理它。如果使用文件系统路径创建CFURL对象,则应使用CFURLCreateFromFileSystemRepresentation和CFURLCreateFromFileSystemRepresentationRelativeToBase函数,这些函数处理URL路径和文件系统路径之间的细微差别。

this question似乎也是同一个问题。正如one of the answers所示:

  

您需要将NSString转换为CFStringRef,然后调用CFURLCreateWithFileSystemPath;

希望对你有所帮助。