【问题标题】:ios FileManager losing stored data when rebuilding appios FileManager在重建应用程序时丢失存储的数据
【发布时间】:2018-01-24 21:59:31
【问题描述】:

我正在尝试将图像存储在应用程序的文档文件夹中,以便用户可以在以后的任何时间检索它们。这是我存储它们的代码:

func store(_ image: UIImage) -> String {
    let imageName = "\(Date().timeIntervalSince1970)"
    let imagePath = "\(documentasPath)/\(imageName).png"

    let imageData = UIImagePNGRepresentation(image)

    fileManager.createFile(atPath: imagePath, contents: imageData, attributes: nil)

    return imagePath
}

这是我从存储中检索图像的代码:

func retrieveImage(from path: String) -> UIImage? {

    guard fileManager.fileExists(atPath: path) else {
        return nil
    }

    return UIImage(contentsOfFile: path)
}

它似乎工作正常,除非我从 xcode 重建应用程序。然后我存储的所有图像都消失了(尽管我存储的指向它们的所有路径仍然存在且正确)。

这是默认文件管理器的一些行为吗?有没有办法避免这种情况发生?我希望仅在手动或卸载应用程序时删除图像。

谢谢

【问题讨论】:

    标签: ios swift nsfilemanager


    【解决方案1】:

    问题是您存储的是绝对路径。您不能这样做,因为您的应用是沙盒,这意味着(部分)Documents 文件夹的 URL 可以更改。只存储文档name,每次您想保存或写入时,计算 Documents 文件夹的路径再次并附加文档名称并使用它结果作为你的路径。

    【讨论】:

      【解决方案2】:

      改成这个

       func store(_ image: UIImage) -> String {
      
           let imageName = "\(Date().timeIntervalSince1970)"
      
           let documentsUrl = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
      
           var imagePath = documentsUrl.appendingPathComponent("\(imageName).png")
      
           let imageData = UIImagePNGRepresentation(image)
      
           fileManager.createFile(atPath: imagePath, contents: imageData, attributes: nil)
      
           return imagePath
         }
      
      
        func retrieveImage(from path: String) -> UIImage? {
      
            guard fileManager.fileExists(atPath: path) else {
                return nil
            }
      
            return UIImage(contentsOfFile: path)
        }
      

      【讨论】:

        猜你喜欢
        • 2016-09-18
        • 1970-01-01
        • 2011-06-12
        • 2021-08-23
        • 1970-01-01
        • 2020-01-05
        • 2012-04-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多