如何从 Swift 中的备份中排除文件?

How to exclude file from backup in Swift?

我使用 Swift 1.2 时效果很好,因为我将 filePath 用作字符串。现在 Swift 2 希望我们所有人都使用 URL 路径,即使我正在阅读他们的文档,我也无法让它工作。

我有;

var fileName = "myRespondusCSV.csv"

let fileManager = NSFileManager.defaultManager()

let documentsURL = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)


if let documentPath: NSURL = documentsURL.first as NSURL! {

    filePath = documentPath.URLByAppendingPathComponent(fileName)
        print(filePath)        
    } else {
        fileManager.createFileAtPath(filePath!.path!,
                                     contents: ("" as String).dataUsingEncoding(NSUTF8StringEncoding)!,
                                     attributes:nil)
        print("file has been created")
    }
}

func excludeFileFromBackup() {

    var error:NSError?
    //var fileToExcludeh = NSURL.fileReferenceURL(filePath!)

    var fileToExcludeh = fileURLWithPath(filePath)

    let success = fileToExcludeh.setResourceValue(true, forKey: NSURLIsExcludedFromBackupKey, error: &error)
}

我收到“使用未解析的标识符 'fileURLWithPath'!

我应该使用绝对 URL 路径吗?

这应该有效

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

Swift4如果有人需要的话:

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

这适用于 Swift 3。 URL 必须是 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)
}

这是我在 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
}

在 swift 5 中为我运行的代码是...

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

当然你可以把它放在函数或扩展中。