How to exclude a file from backup using Swift 2?

I worked great with Swift 1.2 since I used filePath as a string. Now Swift 2 wants us all to use the URL paths, I can't get this to work even if I read their documents.

I have:

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)
}

I get 'Using Unresolved Identifier' fileURLWithPath '!

Should I use an absolute url?

+4
source share
5 answers

This should work

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

Swift 4, if someone needs it:

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

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)
}
+3

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
}
+1

Code that works for me in Swift 5 ...

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 extension.

0
source

Source: https://habr.com/ru/post/1608115/


All Articles