URLResourceValue 和 setResourceValues Swift 3
URLResourceValue and setResourceValues Swift 3
我正在尝试弄清楚我应该如何使用 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") }
}
我得到的错误是
我使用上面的代码将文件从备份到 iCloud 中排除,并且它在以前的 Swift 版本中工作正常,但在更新到 Xcode 8 之后我就卡住了。
如果有任何帮助或建议,我将不胜感激。
Xcode 建议 "Use struct URLResourceValues and URL.setResourceValues(_:) instead" 提示您编写如下内容:
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") }
}
请尝试。
注意
请注意文件 URL 必须是一个 var - 如果它是一个 let 你会收到奇怪的错误信息(见评论)。
除了 提供的内容之外,请确保您的 URL 是 var 而不是 let。
这就是让我的代码在迁移到 swift 3.
后工作的原因
我正在尝试弄清楚我应该如何使用 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") }
}
我得到的错误是
我使用上面的代码将文件从备份到 iCloud 中排除,并且它在以前的 Swift 版本中工作正常,但在更新到 Xcode 8 之后我就卡住了。
如果有任何帮助或建议,我将不胜感激。
Xcode 建议 "Use struct URLResourceValues and URL.setResourceValues(_:) instead" 提示您编写如下内容:
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") }
}
请尝试。
注意
请注意文件 URL 必须是一个 var - 如果它是一个 let 你会收到奇怪的错误信息(见评论)。
除了
这就是让我的代码在迁移到 swift 3.
后工作的原因