简体   繁体   中英

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 这个

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.

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM