Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude file from backup in Swift?

Tags:

ios

swift

nsurl

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?

like image 730
Slarty Bartfast Avatar asked Sep 19 '15 09:09

Slarty Bartfast


1 Answers

Swift 4 if anyone needs it:

var resourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true
try? fileUrl.setResourceValues(resourceValues)
like image 171
Eli Burke Avatar answered Oct 20 '22 05:10

Eli Burke