OGeek|极客世界-中国程序员成长平台

标题: iOS:防止 .cacheDirectory 中的文件在完全存储警告时被删除 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:44
标题: iOS:防止 .cacheDirectory 中的文件在完全存储警告时被删除

我的问题: 我在缓存目录中有我的 SQLite 数据库文件,并将 isExcludedFromBackup 设置为 true,因为我读过,这样做会阻止 iOS 系统在存储空间满的情况下删除它。但它仍然被删除。这在装有 iOS 10.3.3 的真实设备 iPhone 5s 上的开发中观察到。

SQLite 数据库文件是由 SQLite.swift API 创建的,这可能很重要但不是必需的原因。 https://github.com/StephenCelis/SQLite.swift

使用 SQLite.swift 创建文件:

    let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
    let databaseName = "name.extension"
    let filePath = "\(path)/\(databaseName)"
    self.db = try! Connection(filePath) // creates the file, if it does not exists

设置 isExcludedFromBackup 标志:

func excludeSQLiteFileFromBackup(path: String) {
    let exists = FileManager.default.fileExists(atPath: path)
    if !exists {
        MyLogger.log("excludeSQLiteFileFromBackup: file not created yet.", aClass: self.classForCoder)
        return
    }

    var url = URL(fileURLWithPath: path)
    do {
        var resourceValues = URLResourceValues()
        resourceValues.isExcludedFromBackup = true
        try url.setResourceValues(resourceValues)
    } catch let error as NSError {
        MyLogger.log("excludeSQLiteFileFromBackup: \(error)", aClass: self.classForCoder)
    }
}

这是使用相同的 filePath 调用的,它在第一个代码块中提供给 Connection。我还通过在将其设置为 true 之前和之后从该文件中获取 ResourceValues 来检查标志是否设置正确,并且它得到了正确的更改。

因为它需要离线使用,所以应该符合商店指南。

问题:

  1. 对吗,isExcludedFromBackup 阻止了iOS系统删除文件?
  2. 如果没有,如何防止系统删除它?由于指导方针,我认为我无法将文件存储在 .documentsDirectory 中,并且我不知道应该使用哪个目录。我更喜欢不需要重新定位数据库文件的解决方案。
  3. 如果是 (@1.) 为什么它在我的情况下不起作用,我该如何解决?



Best Answer-推荐答案


1) 不,isExcludedFromBackup = true表示用户备份手机时不会包含这个文件,不知道为什么你认为它不会被删除。

2) 解决问题的正确方法是将数据库重新定位到 Documents 目录,您无法控制 caches 目录,iOS 会在需要时将其清除。

关于iOS:防止 .cacheDirectory 中的文件在完全存储警告时被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48749185/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4