从字符串格式文件路径访问os x app bundle之外的文件

时间:2015-12-29 17:48:35

标签: swift macos

在我的应用程序中,我有一个AMPathPopUpButton,它以字符串形式返回文件的位置(格式:〜/ Desktop / file.pdf)。我想制作一个这个文件的CGPDFDocument。但我的应用程序似乎无法访问该文件,因为它在我的应用程序包之外。所以CGPDFDocument总是为零。我如何使用此文件路径字符串来创建有效的CGPDFDocument?谢谢你的帮助!

我的一些代码:( MyName当然是我的实际名称)(CFUrl例如:file:///Users/MyName/Desktop/file.pdf)

 var document:  CGPDFDocumentRef!
 filepath = String("/Users/MyName" + String(filepath.characters.dropFirst()))
        let url = NSURL.fileURLWithPath(filepath)
        let CFUrl = url as CFURL
        document =  CGPDFDocumentCreateWithURL(CFUrl)

1 个答案:

答案 0 :(得分:0)

以下是最终答案:

  1. 首先将文件路径字符串转换为NSString并使用NSString函数完成如下路径:

    let path : NSString = filepath as NSString let thePath = path.stringByExpandingTildeInPath

  2. 现在你可以创建一个NSURL,将其转换为CFURL并制作一个CGPDFDocument:

    let url = NSURL.fileURLWithPath(thePath) let CFUrl = url as CFURL document = CGPDFDocumentCreateWithURL(CFUrl)

相关问题