Xcode 从恢复图像。在Swift中写入文件

Xcode 从恢复图像。在Swift中写入文件,xcode,swift,swift2,Xcode,Swift,Swift2,我正在尝试从恢复图像。写入文件 以下是我用来保存它的代码: view.pdfData.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.URLByAppendingPathComponent("test.pdf"), atomically: true) view.pdfData.writeToFile(

我正在尝试从恢复图像。写入文件

以下是我用来保存它的代码:

view.pdfData.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.URLByAppendingPathComponent("test.pdf"), atomically: true) 
        view.pdfData.writeToFile("test", atomically: false)
        print(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.path!)
下面是我试图恢复它的方法:

 let path: String? = NSBundle.mainBundle().pathForResource("test", ofType: "pdf", inDirectory: "DirectoryName/Images")
        let imageFromPath = UIImage(contentsOfFile: path!)!
        self.imageview.image = imageFromPath
但我一直得到一个断点:


尼尔

你需要像写作一样建立阅读路径。使用
NSBundle.mainBundle()

let path = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.URLByAppendingPathComponent("test.pdf").path
let imageFromPath = UIImage(contentsOfFile: path!)!

另外,请使用
强制展开选项通常是个坏主意。它不允许你的应用程序优雅地处理获取零值的问题,并且会导致崩溃(就像你发布的那样)。正确的方法是这样的

if let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first,
    let path = documentsURL.URLByAppendingPathComponent("test.pdf").path,
    let imageFromPath = UIImage(contentsOfFile: path) {
        print("Loaded Image")
} else {
    print("Unable to load image")
}

你期待什么?应用程序包和文档目录是完全不同的位置。@当我更改inDirectory时,断点位于不同的行上。再说一次,你期待什么?无法从应用程序包中读取
文档中写入的文件。不要对路径进行“硬编码”。@vadian有没有办法将其保存到其他位置,因为我需要恢复图像。从文件写入的位置恢复文件:获取
URLsForDirectory
并附加文件名,与写入例程中的过程相同。我会打印出“无法加载图像”它无法找到图像,即使我已将其保存为“test.pdf”,但我读取的是png而不是pdf。pdf不是文件类型。即使我将其更改为png保存和恢复,它也“无法加载图像”@NiallKehoe您需要使用QLPreviewController()打开pdf或webview@NiallKehoe另一个选项是从视图中保存快照