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

时间:2016-09-13 08:37:10

标签: ios swift nsfilemanager

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

    }

导致这种情况的原因是什么?

2 个答案:

答案 0 :(得分:8)

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

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

}

答案 1 :(得分:1)

重新安装应用程序时,文档目录将更改。您不应该保存完整路径,而是保存文档目录中的相对路径。