2

I try to write code which changes property of file, but I get a compiler error.

Here is the code:

func addSkipBackupAttributeToItemAtURL(URL: NSURL) -> Bool{

    let fileManager = NSFileManager.defaultManager()
    assert(fileManager.fileExistsAtPath(URL.absoluteString))

    var error:NSError?
    let success:Bool = try? URL.setResourceValue(NSNumber(bool: true),forKey: NSURLIsExcludedFromBackupKey)

    if !success {
        print("Error excluding \(URL.lastPathComponent) from backup \(error)")
    } else {
        print("File at path \(URL) was succesfully updated")
    }

    return success
}

and the error is:

Cannot convert value of type '()?' to specified type 'Bool'

How can I fix it?

Eric Aya
  • 68,765
  • 33
  • 165
  • 232
Alexey K
  • 5,649
  • 16
  • 51
  • 102
  • Note that `URL.absoluteString` most probably should be `URL.path`, compare for example http://stackoverflow.com/questions/34135305/nsfilemanager-defaultmanager-fileexistsatpath-returns-false-instead-of-true. – Martin R Dec 10 '15 at 20:32

1 Answers1

2

Call to url?.setResourceValue(NSNumber(bool: true),forKey: NSURLIsExcludedFromBackupKey) doesn't return a Bool. You are expecting a Bool as response. Thats the reason for error.

Apple documentation for setResourceValue method says

In Swift, this method returns Void and is marked with the throws keyword to indicate that it throws an error in cases of failure.

do {
    try url?.setResourceValue(NSNumber(bool: true), forKey: NSURLIsExcludedFromBackupKey)

    //...
}
catch let error as NSError {
     //...
}
R P
  • 1,133
  • 2
  • 10
  • 20
  • Thanks! How can I achieve this https://developer.apple.com/library/ios/qa/qa1719/_index.html then ? – Alexey K Dec 10 '15 at 20:25