ios - 如何在 iOS 中获得一个不会过期的缓存?

标签 ios swift caching

我正在使用缓存框架 在我的应用程序中进行缓存。缓存框架可以提供带有过期选项的混合存储。我已经为两种存储(磁盘和内存)设置了 .never,但缓存仍然会过期。

在我的应用程序中,我需要永久缓存一些 Data(),并在必要时更新它(但不经常)。获取此缓存的速度不是那么必要。

是否可以使用这个框架?我可以只使用 DiskStorage 而不是 Storage 吗?我认为它可能会过期,因为它一直保存到系统内存(我认为是 RAM)中,因此 iOS 可以在需要时清理它,但 iOS 可以清理磁盘存储吗?

最佳答案

所以,我在 Apple 指南中找到了一些关于此的内容:

Use the "do not back up" attribute for specifying files that should remain on device, even in low storage situations. Use this attribute with data that can be recreated but needs to persist even in low storage situations for proper functioning of your app or because customers expect it to be available during offline use. This attribute works on marked files regardless of what directory they are in, including the Documents directory. These files will not be purged and will not be included in the user's iCloud or iTunes backup. Because these files do use on-device storage space, your app is responsible for monitoring and purging these files periodically.

我为此编写了简单的函数:

func setExludedFromBackup() {
    var url = try? FileManager.default.url(
        for: .documentDirectory,
        in: .userDomainMask,
        appropriateFor: nil,
        create: true).appendingPathComponent("MyFolder")
    var resuorceValues = URLResourceValues()
    resuorceValues.isExcludedFromBackup = true
    try? url?.setResourceValues(resuorceValues)
 // print(try? url?.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup)
 // you can check if your directory excluded from backup (it excluded if "Optional(Optional(true))" printed)
}

是的,是Documents文件夹,因为其他文件夹还在继续清理。

您只需在某处调用此函数(我使用过 AppDelegate),并在调用它之前检查目录是否已从备份中排除。如果 iOS 内存不足,可以保护 Documents 目录中的“MyFolder”不被删除!因此,只要我愿意,我的数据就可以使用。 但是你也必须包括事后删除机制,因为这些数据永远不会被自动删除,设备上的内存空间也不会被释放。在我的例子中,我只是使用了缓存框架的expiry属性

附言我不确定 Apple 将如何对此使用react,在 AppStore 检查您的应用程序时,请告诉他们您的应用程序中的离线使用情况以及您对文档文件夹所做的操作,不要忘记描述您的删除机制。我希望这不会违反 Apple 指南,并且应用不会被拒绝。

关于ios - 如何在 iOS 中获得一个不会过期的缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51803131/

相关文章:

ios - 在 OperationQueue(或替代 API,例如 PromiseKit、Combine Framework)中设置背压

Swift Print 函数格式化

java - 在多线程环境中使用缓存映射是否安全?

c# - 为什么我必须将我的对象放入 HttpContext 缓存中两次才能永久保留它?

java - 有没有办法预缓存网页以供使用 Android WebView 查看?

html - 位置:iPhone iOS 中的固定页脚

ios - 在 Swift 中使用 Google Calendar API 时收到错误 "Daily Limit For Unauthenticated Use Exceeded"

arrays - 传递包含类或结构的数组

ios - UIScrollView不显示动态添加的内容

ios - 在 Internet 连接可用后做某事的最佳方法