NSSearchPathForDirectoriesInDomains 在模拟器上工作但不在设备上工作

NSSearchPathForDirectoriesInDomains working on simulator but not on device

我正在尝试保存并稍后从磁盘加载图像。以下在模拟器上运行,但是当我在设备上测试时,我得到 unexpectedly found nil while unwrapping an Optional value.

正在将图像保存到磁盘:

let sketchData: NSData = UIImagePNGRepresentation(sketch)
let destinationFolder: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let sketchPath: String = "\(destinationFolder)\(currentProjectID).png"
defaults.setObject(sketchPath, forKey: "sketchpath")
sketchData.writeToFile(sketchPath, atomically: true)

正在从磁盘加载图像:

let sketchPath: String = defaults.objectForKey("sketchpath") as String
let image = UIImage(contentsOfFile: sketchPath)

这是一个示例路径。它在保存和加载方面是相同的,所以问题不是试图从不同的文件路径加载。

/var/mobile/Containers/Data/Application/72EDBC3D-F9D8-4108-8A64-751A10FF1E71/Documents4.png

保存到实际设备是否需要不同的文件路径?

您只是忘记在文件夹和文件名之间添加“/”:

let sketchPath: String = "\(destinationFolder)/\(currentProjectID).png"

您应该使用 stringByAppendingPathComponent 和 stringByAppendingPathExtension:

let currentProjectID = "Test"
// you can also use NSFileManager's method URLsForDirectory to find the device's DocumentDirectory
let destinationFolder =  (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL).path!
let sketchPath = destinationFolder.stringByAppendingPathComponent(currentProjectID).stringByAppendingPathExtension("png")!

您还将其保存为 NSData,因此您应该将其加载为 NSData

let imageData: NSData = UIImagePNGRepresentation(UIImage(data: NSData(contentsOfURL: NSURL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!)! ))

imageData.writeToFile(sketchPath, atomically: true)

let loadedImage = UIImage(data: NSData(contentsOfFile: sketchPath)! )!!