ios FileManager 在重建应用程序时丢失存储的数据

标签 ios swift nsfilemanager

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

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 重建应用程序。然后我所有存储的图像都消失了(尽管我存储的所有指向它们的路径仍然存在并且正确)。

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

谢谢

最佳答案

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

关于ios FileManager 在重建应用程序时丢失存储的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48432363/

相关文章:

iOS - NSFIleManager - 如何处理磁盘空间不足

ios - 初始化 UIView 对象时的 dispatch_async

ios - NSFileManager.defaultManager().fileExistsAtPath 返回 false 而不是 true

ios - 适用于 iOS 的 Firebase - 控制台卡在未针对云消息传递进行配置

ios - 在 iOS 设备中启动 YouTube 应用程序

ios - 为什么不透明样式在 SearchBar 上不起作用?

ios - 按下按钮后只显示第一句话

ios - 以编程方式创建目录

当 native 闹钟响起时发送推送通知的 iOS 应用程序

ios - 为 iOS 7 编译 x264