URLResourceValue and setResourceValues ​​Swift 3

I am trying to figure out how I should continue to install foxes under code using Swift 3.

let paths = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true) as NSArray for path in paths { let dir = path as! String print("the paths are \(path)") let urlToExclude = NSURL.fileURL(withPath: dir) do { try urlToExclude.setResourceValue(NSNumber(value: true), forKey: URLResourceKey.isExcludedFromBackupKey) } catch { print("failed to set resource value") } } 

The error I get is this this

I used the code above to exclude files from backup in iCloud, and it worked fine for the previous version of Swift, but after upgrading to Xcode 8, I just got stuck.

I would really appreciate any help or suggestions.

+8
ios ios10 swift3 xcode8 nsurl
source share
2 answers

Xcode's suggestion, β€œUse struct URLResourceValues ​​and URL.setResourceValues ​​(_ :) instead,” suggests you write something like this:

 let paths = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true) for dir in paths { print("the paths are \(dir)") var urlToExclude = URL(fileURLWithPath: dir) do { var resourceValues = URLResourceValues() resourceValues.isExcludedFromBackup = true try urlToExclude.setResourceValues(resourceValues) } catch { print("failed to set resource value") } } 

Give it a try.

Note

Please note that the file url must be var - if it allows you to get strange error messages (see comments).

+22
source share

In addition to what TheEye provides, make sure your URL is a variable, not let.

That is what made my code work after switching to swift 3.

+11
source share

All Articles