How to exclude file from backup with Swift 2?

你说的曾经没有我的故事 提交于 2019-12-05 18:20:48

This should work

        do {
            try filePath.setResourceValue(true, forKey: NSURLIsExcludedFromBackupKey)
        } catch _{
            print("Failed")
        }
Eli Burke

Swift 4 if anyone needs it:

var resourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true
try? fileUrl.setResourceValues(resourceValues)

This is working for Swift 3. URL must be a var.

let urls:[URL] = FileManager.default.urls(for:FileManager.SearchPathDirectory.documentDirectory, in:FileManager.SearchPathDomainMask.userDomainMask)
let appDirectory:URL = urls.last!
var fileUrl:URL = appDirectory.appendingPathComponent("myFile")

var resourceValues:URLResourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true

do
{
    try fileUrl.setResourceValues(resourceValues)
}
catch let error
{
    print(error.localizedDescription)
}

Here is my resolution for it on Swift 3

func addSkipBackupAttributeToItemAtURL(URL:NSURL) -> Bool {
    var success: Bool

    do {
        try URL.setResourceValue(true, forKey:URLResourceKey.isExcludedFromBackupKey)
        success = true
    } catch let error as NSError {
        success = false
        print("Error excluding \(URL.lastPathComponent!) from backup \(error)");
    }
    return success
}

The code that runs for me in swift 5 is...

var file: URL = <# your URL file #>
do {
   var res = URLResourceValues()
   res.isExcludedFromBackup = true
   try file.setResourceValues(res)
} catch {
   print(error)
}

Of course you can put this in a function or an extension.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!