Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URLResourceValue and setResourceValues Swift 3

I'm trying to figure out how i should proceed fox fixing below 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 that i'm getting is this

I used the above code for excluding files from backing up to the iCloud and it used to work fine for previous version of Swift but after updating to Xcode 8 I'm just stuck.

I would really appreciate any help or suggestions.

like image 705
Dushyant Avatar asked Sep 22 '16 04:09

Dushyant


2 Answers

The Xcode suggestion "Use struct URLResourceValues and URL.setResourceValues(_:) instead" is prompting you to 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") }
}

Please try.

NOTE

Please note that the file URL has to be a var - if it's a let you will get strange error messages (see comments).

like image 195
OOPer Avatar answered Nov 16 '22 00:11

OOPer


Additionally to what TheEye provided, make sure your URL is a var and not a let.

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

like image 23
Josh Avatar answered Nov 15 '22 22:11

Josh