gpt4 book ai didi

ios - 重新编译App后保存的文件不见了

转载 作者:搜寻专家 更新时间:2023-10-30 22:30:42 26 4
gpt4 key购买 nike

我正在编写一个 iOS 应用程序(在 Swift 中),其中包含将图片保存到安全位置的选项。一旦选择了图片(来自相机或保存的图像),它就会被写入文件,文件位置保存在 NSUserDefaults 中。当我在杀死它后重新启动应用程序时,我能够重新访问该图像。但是当我再次从 Xcode 运行应用程序时(重新编译后),图像从图像路径中丢失了。

下面附上保存和加载函数

 func getDocumentsURL() -> NSURL {

let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]

return documentsURL
}

func fileInDocumentsDirectory(filename: String) -> String {

let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename)
return fileURL.path!

}


func saveImage (image: UIImage, path: String ) -> Bool{



// let pngImageData = UIImagePNGRepresentation(image)

let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // if you want to save as JPEG
let result = jpgImageData!.writeToFile(path, atomically: true)

return result

}

func loadImageFromPath(path: String) -> UIImage? {

let image = UIImage(contentsOfFile: path)

if image == nil {

print("missing image at: \(path)")
}
print("Loading image from path: \(path)") // this is just for you to see the path in case you want to go to the directory, using Finder.
return image

}

这可能是什么原因造成的?

最佳答案

每次运行后文档目录路径都不同。

仅将文档目录中的相对路径保存到 NSUserDefaults(您附加到 getDocumentsURL() NSURL 的内容)。

因此在您的情况下,您没有在应用程序文档目录中指定子目录,因此下次运行时您唯一需要的是您保存的文件名。

之后,您可以通过以下方式检索保存的图像:

 func loadImageNamed(name: String) -> UIImage? {

let imagePath = fileInDocumentsDirectory(name)
let image = UIImage(contentsOfFile: imagePath)

if image == nil {

print("missing image at: \(path)")
}
print("Loading image from path: \(path)") // this is just for you to see the path in case you want to go to the directory, using Finder.
return image

}

关于ios - 重新编译App后保存的文件不见了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39465596/

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