gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:16:44 31 4
gpt4 key购买 nike

我正在尝试从磁盘保存并稍后加载图像。以下内容适用于模拟器,但当我在设备上测试时,我得到 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)! )!!

关于ios - NSSearchPathForDirectoriesInDomains 在模拟器上工作但不在设备上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28664952/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com