重新编译应用程序后保存的文件已消失

Sid*_*Dev 5 nsfilemanager ios swift

我正在编写一个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

    }
Run Code Online (Sandbox Code Playgroud)

可能是什么导致了这个?

Dej*_*dar 9

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

保存到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

}
Run Code Online (Sandbox Code Playgroud)