Search code examples
iosswiftnsurl

How to exclude file from backup in Swift?


I had this working great with Swift 1.2 as I used the filePath as a string. Now Swift 2 wants us all to use URL paths I can't get this to work even though i'm reading through their docs.

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'm getting a 'Use of unresolved identifier 'fileURLWithPath'!

Should I be using an absolute URL path?


Solution

  • This should work

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