iOS:防止 .cacheDirectory 中的文件在完全存储警告时被删除
<p><p>我的问题:
我在缓存目录中有我的 SQLite 数据库文件,并将 isExcludedFromBackup 设置为 true,因为我读过,这样做会阻止 iOS 系统在存储空间满的情况下删除它。但它仍然被删除。这在装有 iOS 10.3.3 的真实设备 iPhone 5s 上的开发中观察到。</p>
<p>SQLite 数据库文件是由 SQLite.swift API 创建的,这可能很重要但不是必需的原因。 <a href="https://github.com/StephenCelis/SQLite.swift" rel="noreferrer noopener nofollow">https://github.com/StephenCelis/SQLite.swift</a> </p>
<p>使用 SQLite.swift 创建文件:</p>
<pre><code> 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
</code></pre>
<p>设置 isExcludedFromBackup 标志:</p>
<pre><code>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)
}
}
</code></pre>
<p>这是使用相同的 filePath 调用的,它在第一个代码块中提供给 Connection。我还通过在将其设置为 true 之前和之后从该文件中获取 ResourceValues 来检查标志是否设置正确,并且它得到了正确的更改。</p>
<p>因为它需要离线使用,所以应该符合商店指南。</p>
<p>问题:</p>
<ol>
<li>对吗,isExcludedFromBackup 阻止了iOS系统删除文件?</li>
<li>如果没有,如何防止系统删除它?由于指导方针,我认为我无法将文件存储在 .documentsDirectory 中,并且我不知道应该使用哪个目录。我更喜欢不需要重新定位数据库文件的解决方案。</li>
<li>如果是 (@1.) 为什么它在我的情况下不起作用,我该如何解决?</li>
</ol></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>1) 不,<code>isExcludedFromBackup = true</code>表示用户备份手机时不会包含这个文件,不知道为什么你认为它不会被删除。 </p>
<p>2) 解决问题的正确方法是将数据库重新定位到 Documents 目录,您无法控制 caches 目录,iOS 会在需要时将其清除。</p></p>
<p style="font-size: 20px;">关于iOS:防止 .cacheDirectory 中的文件在完全存储警告时被删除,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/48749185/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/48749185/
</a>
</p>
页:
[1]