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?
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.
来源:https://stackoverflow.com/questions/32666765/how-to-exclude-file-from-backup-with-swift-2