【问题标题】:Saved file is gone after recompiling the App重新编译应用程序后保存的文件消失了
【发布时间】:2017-01-20 19:02:27
【问题描述】:

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

    }

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

【问题讨论】:

标签: ios swift nsfilemanager


【解决方案1】:

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

仅将文档目录中的相对路径保存到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

}

【讨论】:

  • 这是否意味着如果不同的应用程序使用相同的名称保存文件,它也将在其他应用程序上可用?
  • @AmeshFernando 不,所有应用都是沙盒,其他应用无法访问您应用的文件,反之亦然。
【解决方案2】:

重新安装应用程序时,文档目录会发生变化。您不应保存完整路径,而应保存文档目录的相对路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 2018-01-09
    • 2014-06-02
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    相关资源
    最近更新 更多