[英]NSSearchPathForDirectoriesInDomains working on simulator but not on device
I'm trying to save, and later load, an image from disk. 我正在尝试从磁盘保存图像,然后再加载。 The following works on the simulator, but when I test on the device, I get unexpectedly found nil while unwrapping an Optional value
. 以下内容适用于模拟器,但是当我在设备上进行测试时, unexpectedly found nil while unwrapping an Optional value
。
Saving image to disk: 将映像保存到磁盘:
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)
Loading image from disk: 从磁盘加载映像:
let sketchPath: String = defaults.objectForKey("sketchpath") as String
let image = UIImage(contentsOfFile: sketchPath)
Here's an example path. 这是一个示例路径。 It's identical in saving and loading, so the issue is not trying to load from a different file path. 保存和加载相同,因此问题不在于尝试从其他文件路径加载。
/var/mobile/Containers/Data/Application/72EDBC3D-F9D8-4108-8A64-751A10FF1E71/Documents4.png
Does saving to an actual device require a different file path? 保存到实际设备是否需要其他文件路径?
You just forgot to add "/" between the folder and the file's name: 您只是忘了在文件夹和文件名之间添加“ /”:
let sketchPath: String = "\(destinationFolder)/\(currentProjectID).png"
You should use stringByAppendingPathComponent and stringByAppendingPathExtension: 您应该使用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")!
You are also saving it as NSData so you should load it as NSData 您还将其另存为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)! )!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.